#!/bin/bash
# KueSync — thorough uninstaller. © 2026 Krometis Analytics.
# Double-click. Removes EVERY KueSync install (any version / location) and kills ALL running
# copies — the agent service, the KS menu app, and anything left over from earlier builds.
set -u

SELF="${BASH_SOURCE[0]}"

# Re-launch with admin privileges (GUI password prompt) if not already root.
if [ "$(id -u)" -ne 0 ]; then
  osascript -e "do shell script \"/bin/bash '${SELF}'\" with administrator privileges" \
    && osascript -e 'display notification "KueSync fully removed." with title "KueSync"' 2>/dev/null
  echo "Done. You can close this window."
  exit 0
fi

# ---- running as root from here ----
CONSOLE_USER="$(stat -f%Su /dev/console 2>/dev/null || true)"
UID_NUM="$(id -u "$CONSOLE_USER" 2>/dev/null || true)"
USER_HOME="$(eval echo ~"$CONSOLE_USER" 2>/dev/null || echo "/Users/$CONSOLE_USER")"
LABELS="com.krometis.kuesync.agent com.krometis.kuesync.menu"

echo "Removing all KueSync installs..."

# 1) Unload launchd jobs by label (per-user GUI + system)
for L in $LABELS; do
  [ -n "$UID_NUM" ] && launchctl bootout "gui/$UID_NUM/$L" 2>/dev/null || true
  launchctl bootout "system/$L" 2>/dev/null || true
  [ -n "$UID_NUM" ] && launchctl disable "gui/$UID_NUM/$L" 2>/dev/null || true
done

# 2) Unload + delete any KueSync plist wherever it lives (current + legacy locations)
for P in \
  /Library/LaunchAgents/com.krometis.kuesync.*.plist \
  /Library/LaunchDaemons/com.krometis.kuesync.*.plist \
  "$USER_HOME"/Library/LaunchAgents/com.krometis.kuesync.*.plist ; do
  [ -e "$P" ] || continue
  [ -n "$UID_NUM" ] && launchctl bootout "gui/$UID_NUM" "$P" 2>/dev/null || true
  rm -f "$P"
done

# 3) Kill every running KueSync process (any version / path)
pkill -f "KueSync.app/Contents/MacOS/KueSync" 2>/dev/null || true
pkill -f "kuesync-agent"                       2>/dev/null || true
pkill -f "kuesync/agent/src/index.js"          2>/dev/null || true
pkill -f "/usr/local/kuesync-agent"            2>/dev/null || true
# anything still bound to the agent port
for PID in $(lsof -ti tcp:37100 2>/dev/null); do kill -9 "$PID" 2>/dev/null || true; done

# 4) Remove installed files (all known locations). Give processes a moment to die first.
sleep 1
rm -rf /usr/local/kuesync-agent

remove_app() {
  local APP="$1"
  [ -e "$APP" ] || return 0
  # 1) Plain root remove (works on older macOS).
  rm -rf "$APP" 2>/dev/null || true
  # 2) macOS 13+ "App Management" can block even root from deleting an app bundle. The user's
  #    Finder IS entitled to manage apps, so ask it (in the user's GUI session) to trash it.
  if [ -e "$APP" ] && [ -n "${UID_NUM:-}" ]; then
    launchctl asuser "$UID_NUM" /usr/bin/sudo -u "$CONSOLE_USER" /usr/bin/osascript \
      -e "tell application \"Finder\" to delete (POSIX file \"$APP\")" >/dev/null 2>&1 || true
  fi
  # 3) Last resort: move it aside into the user's Trash.
  if [ -e "$APP" ]; then
    mkdir -p "$USER_HOME/.Trash" 2>/dev/null || true
    mv -f "$APP" "$USER_HOME/.Trash/KueSync-removed-$(date +%s).app" 2>/dev/null || true
  fi
  [ -e "$APP" ] && echo "Could not auto-remove $APP — open Finder and drag KueSync.app to the Trash." || true
}
remove_app "/Applications/KueSync.app"
remove_app "$USER_HOME/Applications/KueSync.app"

# 5) Forget package receipts (current + any legacy ids)
for ID in com.krometis.kuesync.agent com.krometis.kuesync; do
  pkgutil --forget "$ID" 2>/dev/null || true
done

# 6) Refresh Launch Services so the removed app disappears from Finder/Launchpad
/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister -kill -r -domain local -domain user 2>/dev/null || true

if [ -e /Applications/KueSync.app ] || [ -e "$USER_HOME/Applications/KueSync.app" ]; then
  echo "KueSync removed, but the app bundle still exists — drag KueSync.app to the Trash."
else
  echo "KueSync fully removed — all versions, all running copies, and the app."
fi
exit 0
