#!/bin/bash

# Install or update Antigravity CLI (agy) on Debian/Ubuntu systems.
set -euo pipefail

# Allow running directly as root (no sudo needed) or as a normal user.
if [[ "${EUID}" -eq 0 ]]; then
  sudo() { while [[ "$1" == -* ]]; do shift; done; "$@"; }
  export -f sudo
fi

echo "==> Preparing base dependencies"
sudo apt-get update
sudo apt-get install -y --no-install-recommends ca-certificates curl

install_dir="${HOME}/.local/bin"
agy_binary="${install_dir}/agy"
if [[ ! -d "${install_dir}" ]]; then
  mkdir -p "${install_dir}"
fi

if command -v agy >/dev/null 2>&1; then
  echo "==> Updating Antigravity CLI"
else
  echo "==> Installing Antigravity CLI"
fi
curl -fsSL https://antigravity.google/cli/install.sh | bash

if ! command -v agy >/dev/null 2>&1 && [[ -x "${agy_binary}" ]]; then
  export PATH="${install_dir}:$PATH"
fi

if ! command -v agy >/dev/null 2>&1; then
  echo "agy install finished, but agy is not available in PATH."
  echo "If your shell does not source .bashrc/.zshrc, run:"
  echo "  export PATH=\"${install_dir}:\$PATH\""
  exit 1
fi

if [[ -f "${HOME}/.bashrc" ]] && ! grep -qF 'export PATH="$HOME/.local/bin:$PATH"' "${HOME}/.bashrc"; then
  echo 'export PATH="$HOME/.local/bin:$PATH"' >> "${HOME}/.bashrc"
fi

if [[ -f "${HOME}/.zshrc" ]] && ! grep -qF 'export PATH="$HOME/.local/bin:$PATH"' "${HOME}/.zshrc"; then
  echo 'export PATH="$HOME/.local/bin:$PATH"' >> "${HOME}/.zshrc"
fi

if command -v agy >/dev/null 2>&1; then
  echo "==> AGY command available: $(command -v agy)"
elif [[ -x "${agy_binary}" ]]; then
  echo "==> AGY command available at ${agy_binary}"
else
  echo "agy install finished, but agy is not available in PATH."
  echo "If your shell does not source .bashrc/.zshrc, run:"
  echo "  export PATH=\"${install_dir}:\$PATH\""
  exit 1
fi
