#!/usr/bin/env bash
# WakeDesk uninstaller for Raspberry Pi / Debian-based Linux
# Removes the wakedesk-rpi package and configuration left behind by the
# installer. By default this PRESERVES the device's identity and license
# activation (Device ID, registered keypair, API token) so reinstalling
# WakeDesk does not create a new, unregistered device.
#
# Usage:
#   sudo bash uninstall_wakedesk.sh                 # remove WakeDesk, keep device identity/activation and backups
#   sudo bash uninstall_wakedesk.sh --all           # also delete saved backups
#   sudo bash uninstall_wakedesk.sh --purge-identity [--all]
#                                                    # also wipe Device ID / license activation
#                                                    # (use only when permanently decommissioning this device)
set -euo pipefail

# ── Colours ───────────────────────────────────────────────────────────────────
if [ -t 1 ]; then
  RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'
  CYAN='\033[0;36m'; BOLD='\033[1m'; RESET='\033[0m'
else
  RED=''; GREEN=''; YELLOW=''; CYAN=''; BOLD=''; RESET=''
fi

info()    { echo -e "${CYAN}  →${RESET} $*"; }
success() { echo -e "${GREEN}  ✓${RESET} $*"; }
warn()    { echo -e "${YELLOW}  ⚠${RESET} $*"; }
die()     { echo -e "\n${RED}  ✗ ERROR:${RESET} $*\n" >&2; exit 1; }

REMOVE_BACKUPS=false
PURGE_IDENTITY=false
for arg in "$@"; do
  case "$arg" in
    --all) REMOVE_BACKUPS=true ;;
    --purge-identity) PURGE_IDENTITY=true ;;
  esac
done

echo ""
echo -e "${BOLD}╔══════════════════════════════════════════╗${RESET}"
echo -e "${BOLD}║        WakeDesk Uninstaller              ║${RESET}"
echo -e "${BOLD}╚══════════════════════════════════════════╝${RESET}"
echo ""

# ── Root / sudo setup ─────────────────────────────────────────────────────────
if [[ "$EUID" -eq 0 ]]; then
  SUDO=""
else
  command -v sudo >/dev/null 2>&1 \
    || die "This script requires root or sudo.\n  Run: sudo bash uninstall_wakedesk.sh"
  SUDO="sudo"
fi

# ── Stop and disable services ────────────────────────────────────────────────
info "Stopping WakeDesk services..."
$SUDO systemctl stop wakedesk wakedesk-host 2>/dev/null || true
$SUDO systemctl disable wakedesk wakedesk-host 2>/dev/null || true
success "Services stopped"

# ── Remove the package(s) ────────────────────────────────────────────────────
echo ""
REMOVED_TRANSPORT=false
for pkg in wakedesk-rpi wakedesk; do
  if dpkg -l "$pkg" 2>/dev/null | grep -q '^ii'; then
    info "Removing $pkg package..."
    $SUDO apt-get remove --purge -y "$pkg"
    success "Package removed"
    REMOVED_TRANSPORT=true
  fi
done
$REMOVED_TRANSPORT || warn "WakeDesk transport package not found (already removed?)"

if dpkg -l wakedesk-host 2>/dev/null | grep -q '^ii'; then
  info "Removing wakedesk-host package..."
  $SUDO apt-get remove --purge -y wakedesk-host
  success "Package removed"
fi

# ── Clean up leftover configuration ──────────────────────────────────────────
echo ""
info "Removing configuration..."

PATHS_TO_REMOVE=(
  /etc/wakedesk-host
  /etc/sudoers.d/wakedesk-host
)

for p in "${PATHS_TO_REMOVE[@]}"; do
  if [[ -e "$p" ]]; then
    $SUDO rm -rf "$p"
    success "Removed $p"
  fi
done

# Device identity and license activation (Device ID, registered keypair,
# API token). Preserved by default so reinstalling WakeDesk reconnects to
# the same registered device instead of creating a new one.
IDENTITY_PATHS=(
  /var/lib/wakedesk
  /var/lib/wakedesk-host
  /root/.config/wakedesk
)
if $PURGE_IDENTITY; then
  warn "Purging device identity and license activation (--purge-identity)..."
  for p in "${IDENTITY_PATHS[@]}"; do
    if [[ -e "$p" ]]; then
      $SUDO rm -rf "$p"
      success "Removed $p"
    fi
  done
else
  info "Keeping device identity and license activation (Device ID stays the same)."
  info "Use --purge-identity to wipe it when permanently decommissioning this device."
fi

# Per-user config and (optionally) backups
for home in /home/*; do
  [[ -d "$home" ]] || continue
  user="$(basename "$home")"
  if [[ -d "$home/.config/wakedesk" ]]; then
    if $PURGE_IDENTITY; then
      $SUDO rm -rf "$home/.config/wakedesk"
      success "Removed $home/.config/wakedesk"
    else
      info "Kept $home/.config/wakedesk (use --purge-identity to remove)"
    fi
  fi
  if $REMOVE_BACKUPS && [[ -d "$home/wakedesk-backups" ]]; then
    $SUDO rm -rf "$home/wakedesk-backups"
    success "Removed $home/wakedesk-backups"
  elif [[ -d "$home/wakedesk-backups" ]]; then
    info "Kept $home/wakedesk-backups (use --all to remove)"
  fi
done

$SUDO systemctl daemon-reload || true

echo ""
echo -e "${BOLD}──────────────────────────────────────────${RESET}"
echo -e "${GREEN}${BOLD}  WakeDesk has been removed.${RESET}"
echo -e "${BOLD}──────────────────────────────────────────${RESET}"
echo ""
echo "  To reinstall, run: sudo bash install_wakedesk.sh"
echo ""
