#!/usr/bin/env bash
# Removes Tunnelry from this server. Run as root:
#
#   ./uninstall.sh --yes            removes the application, its system files and the unprivileged user;
#                                   KEEPS the certificate authority and the VPN configuration (/etc/tunnelry,
#                                   /etc/openvpn/server), so existing client profiles stay valid
#   ./uninstall.sh --yes --purge    removes those as well (every issued profile stops working; cannot be undone)
#
# Installed packages (nginx, php, openvpn, ...) are left alone: other things may use them.
set -euo pipefail

YES=0; PURGE=0
for arg in "$@"; do
  case "$arg" in
    --yes) YES=1 ;;
    --purge) PURGE=1 ;;
    -h|--help) sed -n '2,10p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;;
    *) echo "unknown option: $arg" >&2; exit 2 ;;
  esac
done

[ "$(id -u)" = 0 ] || { echo "run as root" >&2; exit 1; }
[ "$YES" = 1 ] || { echo "this removes Tunnelry; run again with --yes to confirm (see --help)" >&2; exit 1; }

echo "==> Stopping services"
systemctl disable --now openvpn-server@server >/dev/null 2>&1 || true
systemctl disable --now tunnelry-firewall.service >/dev/null 2>&1 || true
for unit in $(systemctl list-units --all --plain --no-legend 'tunnelry-rollback-*' 2>/dev/null | awk '{print $1}'); do
  systemctl stop "$unit" >/dev/null 2>&1 || true
done
nft delete table inet tunnelry >/dev/null 2>&1 || true
nft delete table ip tunnelry_nat >/dev/null 2>&1 || true

echo "==> Removing the web interface"
rm -f /etc/nginx/sites-enabled/tunnelry /etc/nginx/sites-available/tunnelry /etc/nginx/tunnelry-access.conf
for pool in /etc/php/*/fpm/pool.d/tunnelry.conf; do
  [ -e "$pool" ] || continue
  rm -f "$pool"
  version="$(echo "$pool" | sed -n 's|/etc/php/\([0-9.]*\)/fpm/.*|\1|p')"
  systemctl reload "php${version}-fpm" >/dev/null 2>&1 || true
done
systemctl reload nginx >/dev/null 2>&1 || true

echo "==> Removing system files"
rm -f /etc/sudoers.d/tunnelry /etc/systemd/system/tunnelry-firewall.service /etc/sysctl.d/99-tunnelry.conf
rm -rf /etc/systemd/system/openvpn-server@server.service.d
if [ -e /etc/unbound/unbound.conf.d/tunnelry.conf ]; then
  rm -f /etc/unbound/unbound.conf.d/tunnelry.conf
  systemctl restart unbound >/dev/null 2>&1 || true
fi
systemctl daemon-reload

echo "==> Removing the application"
rm -rf /opt/tunnelry /usr/lib/tunnelry /var/lib/tunnelry /var/log/tunnelry-install.log
getent passwd tunnelry >/dev/null && userdel tunnelry >/dev/null 2>&1 || true
getent group tunnelry >/dev/null && groupdel tunnelry >/dev/null 2>&1 || true

if [ "$PURGE" = 1 ]; then
  echo "==> Purging the certificate authority and the VPN configuration"
  rm -rf /etc/tunnelry /etc/openvpn/server
else
  echo "Kept: /etc/tunnelry (certificate authority, state) and /etc/openvpn/server."
  echo "Use --purge to remove them too."
fi

echo "Tunnelry has been removed."
