#!/usr/bin/env bash
# uninstall-macos.sh - remove kraken-player from a Mac, reversing install-macos.sh
# and appliance-macos.sh. Run with sudo:
#
#   sudo bash uninstall-macos.sh              # removes everything incl. /usr/local/var/kraken-player
#   sudo KEEP_DATA=1 bash uninstall-macos.sh  # keeps config + pairing
#
# Idempotent: every step tolerates the thing already being gone.
set -euo pipefail

if [[ $EUID -ne 0 ]]; then
  echo "Run with sudo: sudo $0" >&2
  exit 1
fi

VAR="/usr/local/var/kraken-player"
PLIST="/Library/LaunchAgents/com.whitecore.kraken-player.plist"
SUDOERS="/etc/sudoers.d/kraken-player"
KEEP_DATA="${KEEP_DATA:-0}"

GUI_USER="${SUDO_USER:-$(stat -f%Su /dev/console 2>/dev/null || echo root)}"
GUI_UID="$(id -u "$GUI_USER" 2>/dev/null || echo 0)"

echo "==> Stopping + unloading the LaunchAgent..."
if [[ "$GUI_UID" != "0" ]]; then
  launchctl bootout "gui/$GUI_UID" "$PLIST" >/dev/null 2>&1 || true
fi
rm -f "$PLIST"

echo "==> Removing the appliance sudoers drop-in..."
rm -f "$SUDOERS"

# Legacy layout: older installs put the binary in /usr/local/bin.
rm -f /usr/local/bin/kraken-player

if [[ "$KEEP_DATA" == "1" ]]; then
  # Keep config + pairing; remove only the binary + detector venv.
  rm -rf "$VAR/bin"
  echo "==> Kept $VAR/config.json + cache (KEEP_DATA=1)."
else
  echo "==> Removing $VAR (binary, config, pairing, detector venv)..."
  rm -rf "$VAR"
fi

echo
echo "Done. kraken-player removed. (Sleep/screensaver + autologin settings from"
echo "appliance-macos.sh are left as-is; revert them in System Settings if wanted.)"
