#!/usr/bin/env bash
# ziactl uninstall — fully remove zia-forsuryaos and (optionally) per-user
# state. Equivalent to `apt purge zia-forsuryaos` plus cleanup of the runtime
# directories the bridge writes to under $XDG_STATE_HOME / $XDG_CONFIG_HOME.
#
# Invoked by the ziactl wrapper when the user runs `ziactl uninstall`.

set -u

PKG="zia-forsuryaos"
BRIDGE_PORT_DEFAULT=8765

YES=0
KEEP_STATE=0
KEEP_OPENCODE_AUTH=1
DRY_RUN=0
COLOR=1

while [ "$#" -gt 0 ]; do
  case "$1" in
    -y|--yes)              YES=1 ;;
    --keep-state)          KEEP_STATE=1 ;;
    --purge-opencode-auth) KEEP_OPENCODE_AUTH=0 ;;
    --dry-run)             DRY_RUN=1 ;;
    --no-color)            COLOR=0 ;;
    -h|--help)
      cat <<'EOF'
Usage: ziactl uninstall [options]

Fully removes the zia-forsuryaos package and per-user runtime state.

Options:
  -y, --yes               Don't prompt for confirmation.
  --keep-state            Keep ~/.local/state/opencode-bridge and
                          ~/.config/zia-forsuryaos (just remove the package).
  --purge-opencode-auth   Also remove the bundled OpenCode CLI auth/cache
                          (~/.local/share/opencode, ~/.cache/opencode).
                          Skipped by default so other OpenCode installs
                          on this user keep their tokens.
  --dry-run               Show what would happen, change nothing.
  --no-color              Disable ANSI colors.

Steps performed (in order):
  1. Stop the zia-bridge.service systemd --user unit.
  2. SIGTERM/SIGKILL any leftover bridge processes on TCP :8765.
  3. Run `sudo apt-get purge -y zia-forsuryaos` (asks once for sudo).
  4. Remove ~/.local/state/opencode-bridge          (unless --keep-state).
  5. Remove ~/.config/zia-forsuryaos                (unless --keep-state).
  6. Remove ~/.local/share/opencode + ~/.cache/opencode
                                                    (only with --purge-opencode-auth).
EOF
      exit 0
      ;;
    *)
      printf 'ziactl uninstall: unknown option: %s\n' "$1" >&2
      printf 'Try `ziactl uninstall --help`.\n' >&2
      exit 2
      ;;
  esac
  shift
done

if [ "$COLOR" = "1" ] && [ -t 1 ]; then
  C_RED=$'\033[31m'; C_GREEN=$'\033[32m'; C_YEL=$'\033[33m'
  C_BLU=$'\033[34m'; C_BOLD=$'\033[1m';   C_RESET=$'\033[0m'
else
  C_RED=""; C_GREEN=""; C_YEL=""; C_BLU=""; C_BOLD=""; C_RESET=""
fi

step() { printf '%s==>%s %s%s%s\n' "$C_BLU" "$C_RESET" "$C_BOLD" "$1" "$C_RESET"; }
ok()   { printf '    %sok%s   %s\n' "$C_GREEN" "$C_RESET" "$1"; }
warn() { printf '    %swarn%s %s\n' "$C_YEL"   "$C_RESET" "$1"; }
err()  { printf '    %serr%s  %s\n' "$C_RED"   "$C_RESET" "$1" >&2; }
note() { printf '    %s\n' "$1"; }

run_or_print() {
  if [ "$DRY_RUN" = "1" ]; then
    printf '    [dry-run] %s\n' "$*"
    return 0
  fi
  "$@"
}

# Resolve home dirs honoring XDG variables.
USER_HOME="${HOME:-$(getent passwd "$(id -u)" | cut -d: -f6)}"
[ -n "$USER_HOME" ] || { err "cannot resolve \$HOME"; exit 1; }

XDG_STATE="${XDG_STATE_HOME:-$USER_HOME/.local/state}"
XDG_CONFIG="${XDG_CONFIG_HOME:-$USER_HOME/.config}"
XDG_DATA="${XDG_DATA_HOME:-$USER_HOME/.local/share}"
XDG_CACHE="${XDG_CACHE_HOME:-$USER_HOME/.cache}"

BRIDGE_STATE_DIR="$XDG_STATE/opencode-bridge"
ZIA_CONFIG_DIR="$XDG_CONFIG/$PKG"
OPENCODE_DATA_DIR="$XDG_DATA/opencode"
OPENCODE_CACHE_DIR="$XDG_CACHE/opencode"

# ── Banner & confirmation ───────────────────────────────────────────────────

printf '%s%sZia uninstaller%s\n' "$C_BOLD" "$C_BLU" "$C_RESET"
printf 'About to:\n'
printf '  - Stop the zia-bridge.service systemd --user unit\n'
printf '  - Kill any leftover bridge processes on :%d\n' "$BRIDGE_PORT_DEFAULT"
printf '  - %sapt-get purge -y %s%s (needs sudo)\n' "$C_BOLD" "$PKG" "$C_RESET"
if [ "$KEEP_STATE" = "0" ]; then
  printf '  - Remove %s\n' "$BRIDGE_STATE_DIR"
  printf '  - Remove %s\n' "$ZIA_CONFIG_DIR"
else
  printf '  - %sKEEP%s per-user state in %s and %s\n' \
    "$C_YEL" "$C_RESET" "$BRIDGE_STATE_DIR" "$ZIA_CONFIG_DIR"
fi
if [ "$KEEP_OPENCODE_AUTH" = "0" ]; then
  printf '  - Remove %s and %s\n' "$OPENCODE_DATA_DIR" "$OPENCODE_CACHE_DIR"
else
  printf '  - %sKEEP%s OpenCode CLI auth/cache in %s and %s\n' \
    "$C_YEL" "$C_RESET" "$OPENCODE_DATA_DIR" "$OPENCODE_CACHE_DIR"
fi
[ "$DRY_RUN" = "1" ] && printf '  %s(dry-run; no changes will be made)%s\n' "$C_YEL" "$C_RESET"
printf '\n'

if [ "$YES" != "1" ] && [ "$DRY_RUN" != "1" ]; then
  if [ ! -t 0 ]; then
    err "stdin is not a tty; refusing to run without -y/--yes"
    exit 1
  fi
  printf 'Proceed? [y/N] '
  IFS= read -r reply || reply=""
  case "$reply" in
    y|Y|yes|YES) ;;
    *) printf 'Aborted.\n'; exit 1 ;;
  esac
fi

# ── 1. Stop the systemd --user unit ─────────────────────────────────────────

step "Stopping zia-bridge.service"
if command -v systemctl >/dev/null 2>&1; then
  if systemctl --user list-unit-files zia-bridge.service >/dev/null 2>&1; then
    if run_or_print systemctl --user stop zia-bridge.service; then
      ok "service stopped"
    else
      warn "systemctl stop returned non-zero (already stopped?)"
    fi
    run_or_print systemctl --user disable zia-bridge.service >/dev/null 2>&1 || true
  else
    note "zia-bridge.service is not installed for this user — skipping"
  fi
else
  warn "systemctl not found — skipping"
fi

# ── 2. Reap any bridge processes still on :8765 ─────────────────────────────

step "Reaping leftover bridge processes on :$BRIDGE_PORT_DEFAULT"
reap_pids=""
if command -v fuser >/dev/null 2>&1; then
  reap_pids="$(fuser -n tcp "$BRIDGE_PORT_DEFAULT" 2>/dev/null | tr -s ' \t' '\n' | sed '/^$/d' | sort -u)"
fi
if [ -z "$reap_pids" ] && command -v ss >/dev/null 2>&1; then
  reap_pids="$(ss -ltnpH 2>/dev/null | awk -v p=":$BRIDGE_PORT_DEFAULT" '$4 ~ p"$" {print $0}' \
    | grep -oE 'pid=[0-9]+' | cut -d= -f2 | sort -u)"
fi
if [ -z "$reap_pids" ]; then
  note "no listener on :$BRIDGE_PORT_DEFAULT"
else
  for pid in $reap_pids; do
    [ "$pid" -gt 0 ] 2>/dev/null || continue
    cmdline=""
    [ -r "/proc/$pid/cmdline" ] && cmdline="$(tr '\0' ' ' < /proc/$pid/cmdline 2>/dev/null)"
    case "$cmdline" in
      *sdk-bridge/bridge.js*) ;;
      *) note "skipping pid=$pid (not a bridge: $cmdline)"; continue ;;
    esac
    if run_or_print kill -TERM "$pid"; then
      ok "SIGTERM pid=$pid"
    fi
  done
  if [ "$DRY_RUN" != "1" ]; then
    sleep 1
    for pid in $reap_pids; do
      if [ -d "/proc/$pid" ]; then
        kill -KILL "$pid" 2>/dev/null && warn "SIGKILL pid=$pid (did not exit)"
      fi
    done
  fi
fi

# ── 3. apt-get purge ────────────────────────────────────────────────────────

step "Purging Debian package $PKG"
if dpkg -s "$PKG" >/dev/null 2>&1; then
  if [ "$DRY_RUN" = "1" ]; then
    printf '    [dry-run] sudo apt-get purge -y %s\n' "$PKG"
  else
    if [ "$(id -u)" = "0" ]; then
      apt-get purge -y "$PKG"
    elif command -v sudo >/dev/null 2>&1; then
      sudo apt-get purge -y "$PKG"
    else
      err "neither root nor sudo available — cannot purge package"
      exit 1
    fi
    if dpkg -s "$PKG" >/dev/null 2>&1; then
      err "package still installed after purge"
      exit 1
    fi
    ok "package purged"
  fi
else
  note "package $PKG is not installed — skipping"
fi

# ── 4 & 5. Remove per-user state ────────────────────────────────────────────

remove_dir() {
  d="$1"; label="$2"
  if [ -e "$d" ] || [ -L "$d" ]; then
    if run_or_print rm -rf -- "$d"; then
      ok "removed $label ($d)"
    else
      err "failed to remove $d"
    fi
  else
    note "$label already absent ($d)"
  fi
}

if [ "$KEEP_STATE" = "0" ]; then
  step "Removing per-user state"
  remove_dir "$BRIDGE_STATE_DIR" "bridge state"
  remove_dir "$ZIA_CONFIG_DIR"   "user config"
else
  step "Keeping per-user state (--keep-state)"
  note "left $BRIDGE_STATE_DIR and $ZIA_CONFIG_DIR untouched"
fi

# ── 6. OpenCode CLI auth / cache (opt-in) ───────────────────────────────────

if [ "$KEEP_OPENCODE_AUTH" = "0" ]; then
  step "Removing OpenCode CLI auth and cache"
  remove_dir "$OPENCODE_DATA_DIR"  "opencode data"
  remove_dir "$OPENCODE_CACHE_DIR" "opencode cache"
else
  step "Keeping OpenCode CLI auth/cache (default)"
  note "use --purge-opencode-auth to also remove them"
fi

printf '\n%sDone.%s Reinstall any time with:\n' "$C_BOLD" "$C_RESET"
printf '  sudo dpkg -i /path/to/zia-forsuryaos_*.deb && sudo apt-get install -f\n'
exit 0
