#!/usr/bin/env bash
set -euo pipefail
ASSUME_YES=1
PURGE_USER_DATA=0
REMOVE_FONTS=0
usage() {
  cat <<USAGE
Usage: $0 [options]

Remove package-owned TopoSnap files. User settings and optional Kim Jung Chul
Gothic fonts are preserved unless explicitly requested.

Options:
  --interactive-apt      Do not pass -y to apt-get.
  --purge-user-data      Remove TopoSnap UI settings under XDG_CONFIG_HOME/~/.config.
  --remove-fonts         Remove /usr/local/share/fonts/heritage/toposnap.
  -h, --help             Show this help.
USAGE
}
while [[ $# -gt 0 ]]; do
  case "$1" in
    --interactive-apt) ASSUME_YES=0; shift ;;
    --purge-user-data) PURGE_USER_DATA=1; shift ;;
    --remove-fonts) REMOVE_FONTS=1; shift ;;
    -h|--help) usage; exit 0 ;;
    *) echo "Unknown argument: $1" >&2; usage >&2; exit 2 ;;
  esac
done
run_privileged() {
  if [[ ${EUID:-$(id -u)} -eq 0 ]]; then "$@"
  elif command -v sudo >/dev/null 2>&1; then sudo "$@"
  else echo "Root privileges are required and sudo is unavailable." >&2; exit 4
  fi
}
if dpkg-query -W -f='${Status}' toposnap 2>/dev/null | grep -q 'install ok installed'; then
  OLD_VERSION="$(dpkg-query -W -f='${Version}' toposnap 2>/dev/null || true)"
  echo "[TopoSnap] Removing package${OLD_VERSION:+ $OLD_VERSION}"
  if command -v apt-get >/dev/null 2>&1; then
    ARGS=(remove); [[ $ASSUME_YES -eq 1 ]] && ARGS+=(-y); ARGS+=(toposnap)
    run_privileged apt-get "${ARGS[@]}"
  else
    run_privileged dpkg -r toposnap
  fi
else
  echo "[TopoSnap] Package 'toposnap' is not installed."
fi
if [[ $REMOVE_FONTS -eq 1 ]]; then
  run_privileged rm -rf /usr/local/share/fonts/heritage/toposnap
  if command -v fc-cache >/dev/null 2>&1; then run_privileged fc-cache -f; fi
  echo "[TopoSnap] Removed TopoSnap-installed Kim Jung Chul Gothic font directory."
fi
if [[ $PURGE_USER_DATA -eq 1 ]]; then
  if [[ -n "${XDG_CONFIG_HOME:-}" ]]; then CFG="$XDG_CONFIG_HOME/toposnap"
  elif [[ -n "${HOME:-}" ]]; then CFG="$HOME/.config/toposnap"
  else echo "HOME/XDG_CONFIG_HOME is unavailable; cannot purge user settings." >&2; exit 6
  fi
  rm -rf -- "$CFG"
  echo "[TopoSnap] Removed user settings: $CFG"
fi
if [[ -e /usr/lib/toposnap/TopoSnap || -e /opt/toposnap/TopoSnap || -e /usr/bin/toposnap || -e /usr/share/applications/net.heritage-labs.toposnap.desktop ]]; then
  echo "[TopoSnap] Uninstall verification failed: package-owned files remain." >&2
  exit 5
fi
echo "[TopoSnap] Uninstall verified. User drawings were not touched."
