#!/bin/bash
# =============================================================================
#  Safewave Remote Management - macOS teardown (manual, one-click)
#
#  Cleanly reverses install-safewave-remote.command: logs out of the tailnet,
#  uninstalls the tailscaled system daemon, removes the binaries and the scheduled
#  self-removal LaunchDaemon, and deletes the Safewave data folder. One admin prompt.
# =============================================================================
set -uo pipefail

SELF="$0"
if [ "$(id -u)" -ne 0 ]; then
  echo "Requesting administrator rights (one prompt)..."
  osascript -e "do shell script \"/bin/bash \\\"$SELF\\\" --elevated\" with administrator privileges" || {
    echo "Elevation was declined." >&2; exit 1; }
  exit 0
fi

DATA_DIR="/Library/Application Support/Safewave"
LOG="$DATA_DIR/remote-install.log"
say() { echo "$*"; [ -d "$DATA_DIR" ] && echo "$(date '+%F %T')  [UNINSTALL]  $*" >> "$LOG"; }

say "Starting Safewave remote teardown..."

# 1. Log out (ephemeral node auto-drops from the admin console)
[ -x /usr/local/bin/tailscale ] && /usr/local/bin/tailscale logout >/dev/null 2>&1 && say "Logged out of tailnet."

# 2. Remove the tailscaled system daemon + binaries
[ -x /usr/local/bin/tailscaled ] && /usr/local/bin/tailscaled uninstall-system-daemon >/dev/null 2>&1 || true
rm -f /usr/local/bin/tailscale /usr/local/bin/tailscaled
say "Removed tailscaled daemon and binaries."

# 3. Remove the scheduled self-removal LaunchDaemon
launchctl bootout system/com.safewave.selfremove >/dev/null 2>&1 || \
  launchctl unload /Library/LaunchDaemons/com.safewave.selfremove.plist >/dev/null 2>&1 || true
rm -f /Library/LaunchDaemons/com.safewave.selfremove.plist
say "Removed self-removal daemon (if present)."

# 4. Remove leftover Tailscale state + Safewave data
rm -rf /Library/Tailscale
rm -rf "$DATA_DIR"
say "Teardown complete. Nothing Safewave-related should remain."
