#!/bin/bash
# Uninstall Unlock macOS for Grok — macOS bash 3.2, no sudo. MOVES files to a backup folder; never deletes.
#   bash uninstall.sh [--yes] [--keep-data] [--dry-run]
#   curl -fsSL https://unlockmac.app/uninstall.sh | bash            (asks y/N)
#   curl -fsSL https://unlockmac.app/uninstall.sh | bash -s -- --yes
set -u
YES=0; KEEP=0; DRY=0
for a in "$@"; do case "$a" in
  -y|--yes) YES=1;; --keep-data) KEEP=1;; --dry-run) DRY=1;;
  -h|--help) sed -n '2,6p' "$0" 2>/dev/null; exit 0;;
  *) echo "Unknown option: $a"; exit 2;; esac; done
H="${HOME:?}"
STAMP="$(date +%Y-%m-%d-%H%M%S)"
BK="$H/Unlock-uninstalled-$STAMP"
UID_="$(id -u)"
CFG="$H/.config/unlock"; [ -d "$CFG" ] || CFG="$H/.config/jailbreak-mac"
LABELS="com.inventagon.unlock com.inventagon.jailbreak-mac"

echo "Unlock uninstall"
echo "This stops Unlock, removes its background agent, frees this Mac's seat,"
if [ $KEEP -eq 1 ]; then echo "and moves the Unlock program files (your memory and settings stay) to:"
else echo "and moves all Unlock files (program, settings, encrypted memory, logs) to:"; fi
echo "  $BK"
echo "Nothing is deleted. Your own files and reports on the Desktop are not touched."
if [ $YES -ne 1 ]; then
  if [ -r /dev/tty ] && { exec 3</dev/tty; } 2>/dev/null; then
    printf "Continue? [y/N] "; read -r ans <&3 || ans=""; exec 3<&-
    case "$ans" in y|Y|yes|YES) ;; *) echo "Cancelled. Nothing changed."; exit 1;; esac
  else
    echo "No terminal to ask. Re-run with --yes to confirm (e.g. ... | bash -s -- --yes)."; exit 1
  fi
fi
run() { if [ $DRY -eq 1 ]; then echo "  [dry-run] $*"; else "$@"; fi; }
MOVED=""; SKIPPED=""
move() { # move path into the backup, keeping its place under $HOME
  p="$1"; [ -e "$p" ] || [ -L "$p" ] || return 0
  case "$p" in "$H"/*) rel="${p#$H/}";; *) rel="system${p}";; esac
  dest="$BK/$rel"
  if [ $DRY -eq 1 ]; then echo "  [dry-run] move $p"; MOVED="$MOVED
  $p"; return 0; fi
  mkdir -p "$(dirname "$dest")" && mv "$p" "$dest" && MOVED="$MOVED
  $p" || SKIPPED="$SKIPPED
  $p"
}

# 1) stop background agent(s) + bridge + tunnel
echo "Stopping Unlock…"
for L in $LABELS; do
  run launchctl bootout "gui/$UID_/$L" >/dev/null 2>&1 || true
  run launchctl unload "$H/Library/LaunchAgents/$L.plist" >/dev/null 2>&1 || true
done
if [ $DRY -eq 0 ]; then
  pkill -f "jailbreak_mac" >/dev/null 2>&1 || true
  pkill -f "unlock-runner/supervisor.py" >/dev/null 2>&1 || true
  pkill -f "mcp_bundle.py" >/dev/null 2>&1 || true
  pkill -f "cloudflared.*(127\.0\.0\.1|localhost):8777" >/dev/null 2>&1 || true
  pkill -f "Unlock.app/Contents/MacOS/Unlock" >/dev/null 2>&1 || true
fi

# 2) free this Mac's seat (best effort; needs internet)
SEAT="not released (offline or no license on this Mac)"
KEY="$(cat "$CFG/license.key" 2>/dev/null | tr -d ' \n')"
MID="$(cat "$CFG/machine_id" 2>/dev/null | tr -d ' \n')"
URL="$(cat "$CFG/license_url" 2>/dev/null | tr -d ' \n')"
BASE="${URL%/api/*}"; [ -n "$BASE" ] || BASE="https://unlockmac.app"
if [ -n "$KEY" ] && [ -n "$MID" ]; then
  if [ $DRY -eq 1 ]; then SEAT="[dry-run] would release seat ${MID:0:12}"
  elif curl -fsS -m 15 -X POST -H "Content-Type: application/json" \
        -d "{\"license_key\":\"$KEY\",\"action\":\"remove\",\"machine_id\":\"$MID\"}" "$BASE/api/devices" >/dev/null 2>&1; then
    SEAT="released (this Mac no longer counts toward your 3 Macs)"
  fi
fi

# 3) move files
echo "Moving files to $BK …"
[ $DRY -eq 1 ] || mkdir -p "$BK"
for L in $LABELS; do move "$H/Library/LaunchAgents/$L.plist"; done
move "$H/.local/share/jailbreak-mac"; move "$H/.local/share/jailbreak-mac-versions"; move "$H/.local/share/jailbreak-mac.swap"
move "$H/.local/share/unlock-runner"
for f in "$H/.local/bin/jailbreak-mac" "$H/.local/bin/jailbreak-mac-start" "$H/.local/bin/unlock" "$H/.local/bin/unlock-start"; do move "$f"; done
move "$H/Library/Logs/Unlock"
if [ $KEEP -eq 0 ]; then
  move "$H/.config/jailbreak-mac"; move "$H/.config/unlock"
  for d in "$H"/.config/unlock-*; do [ -e "$d" ] && move "$d"; done
  for d in "$H/Library/Application Support/JailBreak your Mac for Grok" "$H/Library/Application Support/JailBreak"; do move "$d"; done
fi
APPNOTE=""
if [ -e "/Applications/Unlock.app" ]; then
  if [ -w "/Applications/Unlock.app" ] && [ -w "/Applications" ]; then move "/Applications/Unlock.app"
  else APPNOTE="Unlock.app is in /Applications but needs your password to move: open Finder → Applications and drag Unlock to the Trash."; fi
fi

# 4) summary
echo
echo "Done. Unlock is uninstalled."
echo "  Background agent: stopped and removed"
echo "  Device seat: $SEAT"
if [ -n "$MOVED" ]; then echo "  Moved to $BK:$MOVED"; else echo "  No Unlock files were found to move."; [ $DRY -eq 1 ] || rmdir "$BK" 2>/dev/null; fi
[ -n "$SKIPPED" ] && echo "  Could not move (left in place):$SKIPPED"
[ -n "$APPNOTE" ] && echo "  $APPNOTE"
[ $KEEP -eq 1 ] && echo "  Kept: your settings and encrypted memory (~/.config/unlock, Application Support). Reinstalling picks them up."
echo
echo "macOS permissions: System Settings → Privacy & Security → Full Disk Access / Automation / Contacts /"
echo "Calendars / Reminders / Photos → remove python3 (and Unlock) if listed."
echo "Your license stays valid if you want Unlock back. Refunds within 7 days: support@unlockmac.app."
if [ -n "$MOVED" ] && [ $DRY -eq 0 ]; then
  echo
  echo "To restore: run the installer again, or move items back from $BK to the same places under your home folder."
  echo "To delete the backup for good:  rm -rf \"$BK\""
  [ $KEEP -eq 0 ] && echo "(Your memory's encryption key stays in your Keychain as \"jailbreak-mac.memory\"; delete it in Keychain Access if you delete the backup.)"
fi
exit 0
