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

DRY_RUN=1
PURGE_DATA=0

for arg in "$@"; do
  case "$arg" in
    --confirm) DRY_RUN=0 ;;
    --purge-data) PURGE_DATA=1 ;;
    --help|-h)
      cat <<'HELP'
GAL-2 Time Contract Linux uninstall script

Default mode:
  dry-run only

Usage:
  ./uninstall_linux.sh
  ./uninstall_linux.sh --confirm
  ./uninstall_linux.sh --confirm --purge-data

Safety:
  Actual removal requires:
    --confirm
    GAL2_ALLOW_DESTRUCTIVE=1

Default behavior preserves:
  /etc/gal2
  /var/lib/gal2
  /var/log/gal2

Purge mode removes preserved config/data/log directories too.
HELP
      exit 0
      ;;
    *)
      echo "Unknown argument: $arg" >&2
      exit 2
      ;;
  esac
done

if [[ "$DRY_RUN" -eq 0 && "${GAL2_ALLOW_DESTRUCTIVE:-0}" != "1" ]]; then
  echo "ERROR: destructive mode requires GAL2_ALLOW_DESTRUCTIVE=1" >&2
  exit 3
fi

if [[ "$DRY_RUN" -eq 0 && "$(id -u)" -ne 0 ]]; then
  echo "ERROR: destructive mode must be run as root via sudo" >&2
  exit 4
fi

GAL2_HOME="${GAL2_HOME:-/opt/gal2}"
GAL2_ETC="${GAL2_ETC:-/etc/gal2}"
GAL2_LIB="${GAL2_LIB:-/var/lib/gal2}"
GAL2_LOG="${GAL2_LOG:-/var/log/gal2}"
SERVICE="${GAL2_SERVICE:-gal2-timecontract.service}"
SERVICE_FILE="${GAL2_SERVICE_FILE:-/etc/systemd/system/$SERVICE}"

run() {
  if [[ "$DRY_RUN" -eq 1 ]]; then
    echo "DRY_RUN: $*"
  else
    "$@"
  fi
}

echo "GAL-2 Linux uninstall"
echo "dry_run=$DRY_RUN"
echo "purge_data=$PURGE_DATA"
echo "gal2_home=$GAL2_HOME"
echo "gal2_etc=$GAL2_ETC"
echo "service=$SERVICE"
echo ""

if command -v systemctl >/dev/null 2>&1; then
  run systemctl stop "$SERVICE" 2>/dev/null || true
  run systemctl disable "$SERVICE" 2>/dev/null || true
else
  echo "INFO: systemctl not found"
fi

if [[ -f "$SERVICE_FILE" ]]; then
  run rm -f "$SERVICE_FILE"
else
  echo "INFO: service file not found: $SERVICE_FILE"
fi

if command -v systemctl >/dev/null 2>&1; then
  run systemctl daemon-reload 2>/dev/null || true
fi

run rm -rf "$GAL2_HOME"

if [[ "$PURGE_DATA" -eq 1 ]]; then
  run rm -rf "$GAL2_ETC"
  run rm -rf "$GAL2_LIB"
  run rm -rf "$GAL2_LOG"
else
  echo "INFO: preserving $GAL2_ETC"
  echo "INFO: preserving $GAL2_LIB"
  echo "INFO: preserving $GAL2_LOG"
fi

echo "DONE"
