#!/usr/bin/env bash
set -Eeuo pipefail

CONFIG_DIR="${KAGEOS_CONFIG_DIR:-/etc/kageos}"
INSTANCES_DIR="${CONFIG_DIR}/instances"
MANAGER="/usr/local/bin/kageos"
YES=0
PURGE=0
ALL=0
INSTANCE_ID=""

die() {
  printf 'ERROR: %s\n' "$*" >&2
  exit 1
}

usage() {
  cat <<'EOF'
kageos production uninstaller

Usage:
  curl -fsSL https://kageos.ai/uninstall-prod.sh | sudo bash -s -- --yes
  curl -fsSL https://kageos.ai/uninstall-prod.sh | sudo bash -s -- --yes --instance instance-02
  curl -fsSL https://kageos.ai/uninstall-prod.sh | sudo bash -s -- --yes --all

Options:
  --yes                  Required to make changes.
  --instance INSTANCE    Remove one instance. May be omitted when only one exists.
  --all                  Remove every registered instance.
  --purge                Also delete the selected instance data.
  --help                 Show this help.

Without --purge, persistent data is kept.
EOF
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --yes|-y) YES=1 ;;
    --purge) PURGE=1 ;;
    --all) ALL=1 ;;
    --instance)
      shift
      [[ $# -gt 0 && -n "${1:-}" ]] || die "--instance requires a value"
      INSTANCE_ID="$1"
      ;;
    --help|-h) usage; exit 0 ;;
    *) die "unknown option: $1" ;;
  esac
  shift
done

[[ "$YES" == "1" ]] || die "refusing to uninstall without --yes"
[[ "${EUID:-$(id -u)}" -eq 0 ]] || die "run with sudo"
[[ -x "$MANAGER" ]] || die "kageos manager not found: $MANAGER"
[[ ! ( "$ALL" == "1" && -n "$INSTANCE_ID" ) ]] || die "use either --all or --instance, not both"

remove_args=()
[[ "$PURGE" == "1" ]] && remove_args+=(--purge)

if [[ "$ALL" == "1" ]]; then
  mapfile -t ids < <(find "$INSTANCES_DIR" -maxdepth 1 -type f -name 'instance-*.env' -printf '%f\n' 2>/dev/null | sed 's/\.env$//' | sort)
  [[ ${#ids[@]} -gt 0 ]] || die "no kageos instances are registered"
  for id in "${ids[@]}"; do
    "$MANAGER" instance remove "$id" "${remove_args[@]}"
  done
else
  if [[ -n "$INSTANCE_ID" ]]; then
    "$MANAGER" instance remove "$INSTANCE_ID" "${remove_args[@]}"
  else
    "$MANAGER" instance remove "${remove_args[@]}"
  fi
fi

remaining=0
if [[ -d "$INSTANCES_DIR" ]]; then
  remaining="$(find "$INSTANCES_DIR" -maxdepth 1 -type f -name 'instance-*.env' | wc -l | tr -d ' ')"
fi
if [[ "$remaining" == "0" ]]; then
  rm -f "${CONFIG_DIR%/}/config.env"
  rmdir "$INSTANCES_DIR" "$CONFIG_DIR" 2>/dev/null || true
  rm -f "$MANAGER"
  printf 'Removed the kageos manager because no instances remain.\n'
fi
