#!/usr/bin/env bash
# Remove Haraka Support agent auto-start (macOS / Linux).
# Usage:
#   bash scripts/uninstall-agent.sh
#   bash scripts/uninstall-agent.sh --purge   # also delete install folder
set -euo pipefail

PURGE=0
for arg in "$@"; do
  case "$arg" in
    --purge|-p) PURGE=1 ;;
    -h|--help)
      echo "Usage: $0 [--purge]"
      echo "  Stops the agent and removes login auto-start."
      echo "  --purge  also deletes the Haraka-Support install directory"
      exit 0
      ;;
  esac
done

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
# Prefer known install homes
CANDIDATES=(
  "$ROOT"
  "$HOME/Haraka-Support"
  "$HOME/Haraka Support"
)

echo "==> Haraka Support — uninstall agent"

case "$(uname -s)" in
  Darwin)
    LABEL="com.haraka.support.agent"
    PLIST="$HOME/Library/LaunchAgents/${LABEL}.plist"
    launchctl bootout "gui/$(id -u)/${LABEL}" 2>/dev/null || true
    launchctl disable "gui/$(id -u)/${LABEL}" 2>/dev/null || true
    rm -f "$PLIST"
    # Legacy Proctor agent if still present
    launchctl bootout "gui/$(id -u)/com.proctor.remote.agent" 2>/dev/null || true
    rm -f "$HOME/Library/LaunchAgents/com.proctor.remote.agent.plist"
    pkill -f 'Haraka-Support/agent/src/index.js' 2>/dev/null || true
    pkill -f 'Haraka Support/agent/src/index.js' 2>/dev/null || true
    echo "Removed macOS LaunchAgent (${LABEL})."
    ;;
  Linux)
    systemctl --user disable --now haraka-support-agent.service 2>/dev/null || true
    rm -f "$HOME/.config/systemd/user/haraka-support-agent.service"
    systemctl --user daemon-reload 2>/dev/null || true
    pkill -f 'Haraka-Support/agent/src/index.js' 2>/dev/null || true
    echo "Removed Linux user systemd service (haraka-support-agent)."
    ;;
  *)
    echo "On Windows run:"
    echo "  powershell -NoProfile -ExecutionPolicy Bypass -File scripts/uninstall-windows.ps1"
    exit 1
    ;;
esac

if [[ "$PURGE" -eq 1 ]]; then
  for dir in "${CANDIDATES[@]}"; do
    if [[ -d "$dir/agent" ]]; then
      echo "==> Deleting $dir"
      rm -rf "$dir"
    fi
  done
  echo "Install folders removed."
else
  echo "Auto-start removed. Files kept (pass --purge to delete folders)."
  echo "Typical folder: $HOME/Haraka-Support"
fi

echo ""
echo "Done. This PC will no longer appear Online after reboot."
