#!/usr/bin/env bash
# ==============================================================================
# 85-destroy-node.sh — Clean Role-Aware Cluster Teardown & Debian 13 Factory Reset
# Removes all Ring2All cluster daemons, packages, data directories, cluster
# /etc/hosts entries, and cluster nftables policies while strictly preserving
# SSH access and the Ring2All NMS ED25519 authorized_keys entry.
# ==============================================================================
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=lib/common.sh
source "${SCRIPT_DIR}/lib/common.sh"

r2a_load_env
r2a_require_root

NODE_ROLE="${NODE_ROLE:-all}"
NODE_HOSTNAME="${NODE_HOSTNAME:-$(hostname 2>/dev/null || echo 'unknown')}"
BRICK_ROOT="${GLUSTER_BRICK_ROOT:-/gluster/brick1}"
export DEBIAN_FRONTEND=noninteractive

r2a_step 1 5 "Stopping and disabling Ring2All cluster services on ${NODE_HOSTNAME} (role=${NODE_ROLE})"
SERVICES_TO_STOP=(
  patroni
  etcd
  postgresql
  postgresql@17-main
  glusterd
  haproxy
  freeswitch
  kamailio
  sbc-kamailio
  rtpengine
  ngcp-rtpengine-daemon
  softswitch-api
  softswitch-monitoring-api
  softswitch-pbx-api
  softswitch-sbc-api
  softswitch-bss-api
  softswitch-bss-client
  softswitch-video-egress
  softswitch-video-sip
  softswitch-video-sfu
  redis-server
  nginx
  r2a-node-agent
  snmpd
)

for svc in "${SERVICES_TO_STOP[@]}"; do
  systemctl stop "$svc" 2>/dev/null || true
  systemctl disable "$svc" 2>/dev/null || true
done

# Unmask PostgreSQL units that 10-pg-ha-node.sh masked for Patroni
systemctl unmask postgresql postgresql@17-main 2>/dev/null || true

r2a_step 2 5 "Unmounting shared storage mounts and purging cluster packages"
for mnt in /var/lib/softswitch/recordings /var/lib/freeswitch/recordings /var/www/softswitch/uploads /usr/share/softswitch/sounds/music /usr/share/freeswitch/sounds/music /mnt/gluster; do
  if mountpoint -q "$mnt" 2>/dev/null; then
    umount -lf "$mnt" 2>/dev/null || true
  fi
done
sed -i '/glusterfs/d' /etc/fstab 2>/dev/null || true

PURGE_PKGS=()
case "$NODE_ROLE" in
  pg_ha)
    PURGE_PKGS=(
      postgresql-17 postgresql-client-17 postgresql-contrib-17 postgresql-17-pgvector
      postgresql-common postgresql-client-common
      etcd-server etcd-client patroni python3-etcd snmpd
    )
    ;;
  storage_gluster)
    PURGE_PKGS=(glusterfs-server glusterfs-client glusterfs-common snmpd)
    ;;
  pbx_admin)
    PURGE_PKGS=(
      softswitch-pbx-api softswitch-pbx-monitoring-api softswitch-pbx-admin
      softswitch-pbx-portal softswitch-pbx-switchboard softswitch-pbx-all
      haproxy glusterfs-client nginx snmpd
    )
    ;;
  pbx_portal_edge)
    PURGE_PKGS=(softswitch-pbx-portal nginx snmpd)
    ;;
  pbx_switchboard_edge)
    PURGE_PKGS=(softswitch-pbx-switchboard nginx snmpd)
    ;;
  pbx_telephony)
    PURGE_PKGS=(
      softswitch-pbx-telephony freeswitch 'freeswitch-*' haproxy glusterfs-client snmpd
    )
    ;;
  sbc_edge)
    PURGE_PKGS=(
      softswitch-sbc-all softswitch-sbc-api softswitch-sbc-admin softswitch-sbc-telephony
      sbc-kamailio kamailio 'kamailio-*' rtpengine ngcp-rtpengine-daemon haproxy nginx snmpd
    )
    ;;
  sbc_media)
    PURGE_PKGS=(ngcp-rtpengine-daemon ngcp-rtpengine-utils rtpengine snmpd)
    ;;
  video_sfu)
    PURGE_PKGS=(
      softswitch-video-all softswitch-video-sfu softswitch-video-sip softswitch-video-egress
      redis-server redis-tools snmpd
    )
    ;;
  bss_admin)
    PURGE_PKGS=(
      softswitch-bss-all softswitch-bss-api softswitch-bss-web softswitch-bss-db
      haproxy nginx snmpd
    )
    ;;
  bss_client)
    PURGE_PKGS=(softswitch-bss-client nginx snmpd)
    ;;
  *)
    PURGE_PKGS=(
      postgresql-17 postgresql-client-17 postgresql-contrib-17 postgresql-17-pgvector
      etcd-server etcd-client patroni python3-etcd
      glusterfs-server glusterfs-client
      haproxy 'softswitch-*' freeswitch sbc-kamailio kamailio rtpengine snmpd
    )
    ;;
esac

# Only purge packages that are actually installed to keep apt-get fast and quiet
INSTALLED_TO_PURGE=()
for pattern in "${PURGE_PKGS[@]}"; do
  while IFS= read -r pkg; do
    [[ -n "$pkg" ]] && INSTALLED_TO_PURGE+=("$pkg")
  done < <(dpkg-query -W -f='${Package}\t${Status}\n' "$pattern" 2>/dev/null | awk '/install ok|deinstall ok|half-configured|half-installed/{print $1}' || true)
done

if (( ${#INSTALLED_TO_PURGE[@]} > 0 )); then
  r2a_info "Purging ${#INSTALLED_TO_PURGE[@]} installed cluster package(s)..."
  apt-get purge -y --allow-change-held-packages "${INSTALLED_TO_PURGE[@]}" || true
  apt-get autoremove -y || true
else
  r2a_info "No cluster packages currently installed to purge."
fi

r2a_step 3 5 "Removing cluster data directories, credentials, agent units, and repository fragments"
rm -rf \
  /var/lib/postgresql \
  /etc/postgresql \
  /var/log/postgresql \
  /var/lib/etcd \
  /etc/default/etcd \
  /etc/patroni \
  /etc/cron.d/patroni-* \
  /etc/cron.d/ring2all-* \
  /etc/modules-load.d/softdog.conf \
  /etc/udev/rules.d/60-watchdog.rules \
  /etc/apt/sources.list.d/pgdg.list \
  /usr/share/postgresql-common/pgdg \
  /var/lib/glusterd \
  /etc/glusterfs \
  "${BRICK_ROOT}" \
  /gluster \
  /etc/softswitch \
  /etc/rtpengine \
  /var/spool/rtpengine \
  /var/log/softswitch/video \
  /usr/local/lib/ring2all-nms-agent \
  /etc/systemd/system/r2a-node-agent.service \
  /var/lib/snmp/snmpd.conf \
  /etc/snmp/snmpd.conf 2>/dev/null || true

udevadm control --reload-rules 2>/dev/null || true
systemctl daemon-reload 2>/dev/null || true

r2a_step 4 5 "Cleaning Ring2All /etc/hosts block and resetting nftables firewall to open clean state"
sed -i '/^# BEGIN RING2ALL CLUSTER HOSTS$/,/^# END RING2ALL CLUSTER HOSTS$/d' /etc/hosts 2>/dev/null || true

if command -v nft >/dev/null 2>&1; then
  cat << 'EOF' > /etc/nftables.conf
#!/usr/sbin/nft -f

flush ruleset

table inet filter {
    chain input   { type filter hook input priority 0; policy accept; }
    chain forward { type filter hook forward priority 0; policy accept; }
    chain output  { type filter hook output priority 0; policy accept; }
}
EOF
  nft -f /etc/nftables.conf 2>/dev/null || nft flush ruleset 2>/dev/null || true
fi

r2a_step 5 5 "Verifying SSH access and NMS ED25519 trust remain intact"
SSH_PRESERVED=true
if [[ ! -s /root/.ssh/authorized_keys ]]; then
  SSH_PRESERVED=false
  r2a_warn "/root/.ssh/authorized_keys is empty; verify SSH access manually."
fi
systemctl is-active --quiet ssh 2>/dev/null || systemctl is-active --quiet sshd 2>/dev/null || true

r2a_ok "Clean teardown complete on ${NODE_HOSTNAME} (role=${NODE_ROLE}); server is ready for fresh Debian 13 reprovisioning."
r2a_result "{\"destroyed\":true,\"hostname\":\"${NODE_HOSTNAME}\",\"role\":\"${NODE_ROLE}\",\"ssh_preserved\":${SSH_PRESERVED}}"
