#!/usr/bin/env bash
# uninstall.sh - remove kraken-player from a Linux / Raspberry Pi box, reversing
# both install.sh (service + sudoers + data) and appliance-pi.sh (kiosk autologin
# + X session). Run as root:
#
#   sudo bash uninstall.sh              # removes everything incl. /var/lib/kraken-player
#   sudo KEEP_DATA=1 bash uninstall.sh  # keeps config + pairing (re-installable in place)
#
# Idempotent: every step tolerates the thing already being gone.
set -euo pipefail

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

DATA_DIR="/var/lib/kraken-player"
SERVICE_FILE="/etc/systemd/system/kraken-player.service"
SUDOERS_FILE="/etc/sudoers.d/kraken-player"
KEEP_DATA="${KEEP_DATA:-0}"

# Kiosk user, so we can undo the per-user autostart. Prefer the appliance marker's
# owner, then the sudo user, then pi.
KIOSK_USER="${KIOSK_USER:-${SUDO_USER:-pi}}"

echo "==> Stopping + disabling the service..."
systemctl stop kraken-player.service >/dev/null 2>&1 || true
systemctl disable kraken-player.service >/dev/null 2>&1 || true
rm -f "$SERVICE_FILE"

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

echo "==> Reversing the kiosk (appliance) setup..."
rm -f /etc/systemd/system/getty@tty1.service.d/autologin.conf
rmdir /etc/systemd/system/getty@tty1.service.d 2>/dev/null || true
systemctl disable kraken-firstboot.service >/dev/null 2>&1 || true
rm -f /etc/systemd/system/kraken-firstboot.service /usr/local/sbin/kraken-firstboot.sh

USER_HOME="$(getent passwd "${KIOSK_USER}" 2>/dev/null | cut -d: -f6 || true)"
if [[ -n "${USER_HOME}" && -d "${USER_HOME}" ]]; then
  # Delete the autostart block the appliance appended to .bash_profile (from the
  # marker line through its closing `fi`), and the managed .xinitrc.
  if [[ -f "${USER_HOME}/.bash_profile" ]]; then
    sed -i '/# kraken-player kiosk autostart/,/^fi$/d' "${USER_HOME}/.bash_profile" || true
  fi
  rm -f "${USER_HOME}/.xinitrc"
fi

systemctl daemon-reload >/dev/null 2>&1 || true

if [[ "${KEEP_DATA}" == "1" ]]; then
  # Keep config + pairing; just drop the appliance marker so a re-install re-enables
  # the service normally.
  rm -f "${DATA_DIR}/appliance.mode"
  echo "==> Kept ${DATA_DIR} (KEEP_DATA=1)."
else
  echo "==> Removing ${DATA_DIR} (binary, config, pairing, detector venv)..."
  rm -rf "${DATA_DIR}"
fi

echo
echo "Done. kraken-player removed. (Swap left disabled if the appliance turned it off;"
echo "re-enable with: sudo dphys-swapfile setup && sudo dphys-swapfile swapon)"
