#!/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 macOS uninstall script

Default mode:
  dry-run only

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

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

Default behavior preserves:
  /etc/gal2
  /usr/local/gal2/var

Purge mode removes:
  /etc/gal2
  /usr/local/gal2
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:-/usr/local/gal2}"
GAL2_ETC="${GAL2_ETC:-/etc/gal2}"
PLIST="${GAL2_PLIST:-/Library/LaunchDaemons/com.gal2.daemon.plist}"
LOG_OUT="${GAL2_LOG_OUT:-/var/log/gal2-daemon.out}"
LOG_ERR="${GAL2_LOG_ERR:-/var/log/gal2-daemon.err}"

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

echo "GAL-2 macOS uninstall"
echo "dry_run=$DRY_RUN"
echo "purge_data=$PURGE_DATA"
echo "gal2_home=$GAL2_HOME"
echo "gal2_etc=$GAL2_ETC"
echo "plist=$PLIST"
echo ""

if [[ -f "$PLIST" ]]; then
  run launchctl bootout system "$PLIST" 2>/dev/null || true
  run launchctl unload "$PLIST" 2>/dev/null || true
  run rm -f "$PLIST"
else
  echo "INFO: plist not found: $PLIST"
fi

if [[ "$PURGE_DATA" -eq 1 ]]; then
  run rm -rf "$GAL2_HOME"
  run rm -rf "$GAL2_ETC"
else
  for path in \
    "$GAL2_HOME/bin" \
    "$GAL2_HOME/docs" \
    "$GAL2_HOME/examples" \
    "$GAL2_HOME/vendor" \
    "$GAL2_HOME/LICENSE.txt"
  do
    if [[ -e "$path" ]]; then
      run rm -rf "$path"
    else
      echo "INFO: not found: $path"
    fi
  done

  echo "INFO: preserving $GAL2_HOME/var"
  echo "INFO: preserving $GAL2_ETC"
fi

if [[ -e "$LOG_OUT" ]]; then
  run rm -f "$LOG_OUT"
else
  echo "INFO: not found: $LOG_OUT"
fi

if [[ -e "$LOG_ERR" ]]; then
  run rm -f "$LOG_ERR"
else
  echo "INFO: not found: $LOG_ERR"
fi

echo "DONE"
