#!/usr/bin/env bash
# Remove RSPC.
#   sudo ./scripts/uninstall.sh            # remove program, keep data (/etc/rspc, /var/lib/rspc)
#   sudo ./scripts/uninstall.sh --purge    # remove everything incl. database, certificates and user
source "$(dirname "${BASH_SOURCE[0]}")/lib.sh"
require_root

PURGE=0
[[ ${1:-} == "--purge" ]] && PURGE=1

if ! is_installed && [[ ! -d $RSPC_HOME && ! -f $RSPC_UNIT ]]; then
  die "RSPC is not installed"
fi

echo "${C_BOLD}${C_RED}RSPC uninstall${C_RESET}"
echo "All routed applications will stop being reachable through this server."
if ((PURGE)); then
  echo "${C_RED}--purge: database, accounts, routes and certificates will be DELETED permanently.${C_RESET}"
else
  echo "Data is kept in $RSPC_ETC and $RSPC_DATA (reinstalling picks it up again)."
fi
reply=""
read -r -p "Type 'uninstall' to confirm: " reply </dev/tty || true
[[ $reply == "uninstall" ]] || die "cancelled"

if [[ -f $RSPC_UNIT ]]; then
  systemctl disable --now "$RSPC_SERVICE" >/dev/null 2>&1 || true
  rm -f "$RSPC_UNIT"
  systemctl daemon-reload
  ok "service removed"
fi
# copy the script dir away if we are running from it
rm -rf "$RSPC_HOME"
ok "program files removed ($RSPC_HOME)"

if ((PURGE)); then
  rm -rf "$RSPC_ETC" "$RSPC_DATA"
  id "$RSPC_USER" &>/dev/null && userdel "$RSPC_USER" 2>/dev/null || true
  ok "data, config and user removed"
else
  ok "data kept: $RSPC_ETC, $RSPC_DATA (remove with --purge)"
  # keep config so a reinstall can be detected, but move it aside so install.sh runs cleanly
  if [[ -f $RSPC_CONFIG ]]; then
    mv -f "$RSPC_CONFIG" "$RSPC_CONFIG.bak"
    ok "config saved as $RSPC_CONFIG.bak"
  fi
fi

if ufw_active; then
  warn "ufw rules for 80/443 and route ports were left in place (ufw status numbered / ufw delete N)"
fi
ok "RSPC uninstalled"
