#!/usr/bin/env bash
# uninstall.sultix.ai — interactive uninstaller for the sultix
# controller. Default keeps the data dir (master.key, db, device-ca)
# so a future reinstall comes back with the same state. Pass
# --purge to wipe everything.
#
# Curl-pipe-bash entry:
#
#   curl -fsSL https://uninstall.sultix.ai | bash
#   curl -fsSL https://uninstall.sultix.ai | bash -s -- --yes --purge

set -euo pipefail

if [ -t 1 ]; then
    C_DIM='\033[2m'; C_RESET='\033[0m'
    C_CYAN='\033[1;36m'; C_GREEN='\033[1;32m'
    C_YELLOW='\033[1;33m'; C_RED='\033[1;31m'
else
    C_DIM=; C_RESET=; C_CYAN=; C_GREEN=; C_YELLOW=; C_RED=
fi

say()  { printf "${C_CYAN}▸${C_RESET} %s\n" "$*"; }
ok()   { printf "${C_GREEN}✓${C_RESET} %s\n" "$*"; }
warn() { printf "${C_YELLOW}!${C_RESET} %s\n" "$*" >&2; }
fail() { printf "${C_RED}✗${C_RESET} %s\n" "$*" >&2; exit 1; }
hr()   { printf "${C_DIM}────────────────────────────────────────────────${C_RESET}\n"; }

ASSUME_YES=0
PURGE=0
PURGE_DOCKER=0    # --purge-docker also removes the docker engine + images
PURGE_PROXY=0     # --purge-proxy also removes caddy
PURGE_POSTGRES=0  # --purge-postgres also removes the postgres container + volume

while [ $# -gt 0 ]; do
    case "$1" in
        --yes|-y)         ASSUME_YES=1 ;;
        --purge)          PURGE=1 ;;
        --purge-docker)   PURGE=1; PURGE_DOCKER=1 ;;
        --purge-proxy)    PURGE_PROXY=1 ;;
        --purge-postgres) PURGE_POSTGRES=1 ;;
        --help|-h)
            cat <<HELP
sultix uninstaller.

By default removes the systemd unit + binary + sultix-ctrl user, but
KEEPS the data dir (so a future reinstall comes back with same state).

Usage:
    curl -fsSL https://uninstall.sultix.ai | bash
    curl -fsSL https://uninstall.sultix.ai | bash -s -- [flags]

Flags:
    --yes, -y         run unattended; never prompt
    --purge           also wipe the data dir (master.key, db, device-ca,
                      ALL chats, ALL secrets — irreversible)
    --purge-docker    --purge AND remove docker engine + all images
    --purge-proxy     also remove caddy (the reverse proxy package)
    --purge-postgres  also stop + remove the sultix-postgres container
                      and the sultix-postgres-data named volume

Examples:
    # Keep data, just remove sultix:
    curl -fsSL https://uninstall.sultix.ai | bash -s -- --yes
    # Wipe everything sultix-related (data, postgres, caddy):
    curl -fsSL https://uninstall.sultix.ai | bash -s -- --yes \\
        --purge --purge-postgres --purge-proxy
    # Reset the host to a virgin state:
    curl -fsSL https://uninstall.sultix.ai | bash -s -- --yes \\
        --purge-docker --purge-postgres --purge-proxy
HELP
            exit 0
            ;;
        *) fail "unknown flag: $1 (try --help)" ;;
    esac
    shift
done

INTERACTIVE=1
[ "$ASSUME_YES" = "1" ] && INTERACTIVE=0
[ ! -e /dev/tty ] && INTERACTIVE=0

confirm() {
    local prompt="$1"
    if [ "$INTERACTIVE" != "1" ]; then return 0; fi
    local ans
    printf "%s [y/N] " "$prompt" > /dev/tty
    read -r ans < /dev/tty || ans=""
    case "${ans}" in
        Y|y|YES|yes) return 0 ;;
        *) return 1 ;;
    esac
}

confirm_destructive() {
    # Two-step prompt for irreversible operations. Requires the
    # user to type a literal token (e.g. "PURGE") before proceeding.
    local prompt="$1" token="$2"
    if [ "$INTERACTIVE" != "1" ]; then return 0; fi
    local ans
    printf "%s\nType %s to confirm: " "$prompt" "$token" > /dev/tty
    read -r ans < /dev/tty || ans=""
    [ "$ans" = "$token" ]
}

case "$(uname -s)" in
    Linux)  OS="linux" ;;
    Darwin) OS="darwin"; fail "darwin uninstall not yet wired — Linux is v1" ;;
    *) fail "unsupported OS: $(uname -s)" ;;
esac

# ── plan summary up front ─────────────────────────────────────────────
hr
printf "${C_CYAN}sultix uninstaller${C_RESET}\n"
printf "  remove binary    /usr/local/bin/sultix\n"
printf "  remove unit      /etc/systemd/system/sultix-controller.service\n"
printf "  remove user      sultix-ctrl\n"
if [ "$PURGE" = "1" ]; then
    printf "  ${C_RED}wipe data dir${C_RESET}  /var/lib/sultix (master.key, db, certs, ALL data)\n"
else
    printf "  KEEP data dir    /var/lib/sultix  (use --purge to wipe)\n"
fi
[ "$PURGE_POSTGRES" = "1" ] && printf "  ${C_RED}remove postgres${C_RESET}  container + volume + creds\n"
[ "$PURGE_PROXY" = "1" ]    && printf "  remove caddy     /etc/caddy/sites-available/sultix.caddyfile (apt remove caddy)\n"
[ "$PURGE_DOCKER" = "1" ]   && printf "  ${C_RED}remove docker${C_RESET}    engine + images + /var/lib/docker (entire daemon)\n"
hr

if [ "$PURGE" = "1" ]; then
    confirm_destructive "This wipes ALL sultix data. Master keys, secrets, chat history — gone forever. No backup is offered by this script (see backup & restore in the admin UI)." "PURGE" \
        || { say "aborted"; exit 0; }
fi
confirm "Proceed with uninstall?" || { say "aborted"; exit 0; }

# ── stop service first ────────────────────────────────────────────────
if systemctl list-unit-files sultix-controller.service >/dev/null 2>&1; then
    say "stopping sultix-controller"
    sudo systemctl stop sultix-controller.service 2>/dev/null || true
    sudo systemctl disable sultix-controller.service 2>/dev/null || true
fi

# ── postgres (before docker, in case --purge-docker is on) ────────────
if [ "$PURGE_POSTGRES" = "1" ]; then
    if command -v docker >/dev/null 2>&1; then
        say "removing postgres container + volume"
        sudo -u sultix-ctrl docker rm -f sultix-postgres 2>/dev/null \
            || docker rm -f sultix-postgres 2>/dev/null || true
        sudo -u sultix-ctrl docker volume rm sultix-postgres-data 2>/dev/null \
            || docker volume rm sultix-postgres-data 2>/dev/null || true
        sudo -u sultix-ctrl docker image rm pgvector/pgvector:pg16 2>/dev/null \
            || docker image rm pgvector/pgvector:pg16 2>/dev/null || true
    fi
    sudo rm -f /home/sultix/.sultix-postgres.env /home/sultix-ctrl/.sultix-postgres.env 2>/dev/null || true
    ok "postgres removed"
fi

# ── caddy (proxy) ─────────────────────────────────────────────────────
if [ "$PURGE_PROXY" = "1" ]; then
    say "removing caddy site config"
    sudo rm -f /etc/caddy/sites-available/sultix.caddyfile
    if command -v caddy >/dev/null 2>&1; then
        sudo systemctl reload caddy 2>/dev/null || true
        say "removing caddy package"
        sudo apt-get purge -y caddy 2>&1 | tail -3 || true
    fi
fi

# ── controller binary + systemd unit + user ───────────────────────────
# Use the controller's own uninstall subcommand if the binary still
# exists — it knows exactly what it created and removes it idempotently.
# Falls back to a manual cleanup for hosts where the binary is broken
# or missing.
if [ -x /usr/local/bin/sultix ]; then
    say "running 'sultix uninstall'$([ "$PURGE" = "1" ] && echo ' --purge')"
    if [ "$PURGE" = "1" ]; then
        sudo /usr/local/bin/sultix uninstall --purge || true
    else
        sudo /usr/local/bin/sultix uninstall || true
    fi
fi

# ── manual cleanup fallback (in case the binary couldn't run) ─────────
sudo rm -f /usr/local/bin/sultix
sudo rm -f /etc/systemd/system/sultix-controller.service
sudo systemctl daemon-reload 2>/dev/null || true
if id sultix-ctrl >/dev/null 2>&1; then
    sudo userdel sultix-ctrl 2>/dev/null || true
fi
if [ "$PURGE" = "1" ]; then
    sudo rm -rf /var/lib/sultix
    sudo rm -rf /opt/sultix
fi

# ── docker engine ─────────────────────────────────────────────────────
if [ "$PURGE_DOCKER" = "1" ]; then
    if command -v docker >/dev/null 2>&1; then
        say "removing docker engine"
        sudo systemctl stop docker.socket docker.service containerd.service 2>/dev/null || true
        sudo systemctl disable docker.socket docker.service containerd.service 2>/dev/null || true
        sudo apt-get purge -y \
            containerd.io docker-buildx-plugin docker-ce docker-ce-cli \
            docker-ce-rootless-extras docker-compose-plugin 2>&1 | tail -3 || true
        sudo apt-get autoremove --purge -y 2>&1 | tail -3 || true
        sudo rm -rf /var/lib/docker /var/lib/containerd /etc/docker
        sudo rm -f /etc/apt/sources.list.d/docker.list /etc/apt/keyrings/docker.gpg
        sudo groupdel docker 2>/dev/null || true
        ok "docker removed"
    fi
fi

hr
ok "sultix uninstalled"
[ "$PURGE" != "1" ] && printf "  data preserved at /var/lib/sultix — reinstall picks up where you left off\n"
[ "$PURGE" = "1" ]  && printf "  ${C_RED}data wiped${C_RESET}  — irreversible\n"
hr
