#!/usr/bin/env bash
# ==============================================================================
# 80-decommission-node.sh — Graceful Single-Node Cluster Departure & Clean Wipe
# Safely drains or transfers leadership before removing a node from an active
# Ring2All HA cluster (Patroni switchover + Etcd member remove, FreeSWITCH call
# drain, GlusterFS/SBC graceful stop), then runs 85-destroy-node.sh to leave
# the Debian 13 server clean while preserving NMS ED25519 SSH access.
# ==============================================================================
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:-unknown}"
NODE_HOSTNAME="${NODE_HOSTNAME:-$(hostname 2>/dev/null || echo 'unknown')}"
NODE_IP="${NODE_IP:-$(hostname -I 2>/dev/null | awk '{print $1}' || echo '')}"

r2a_step 1 2 "Performing graceful cluster departure for ${NODE_HOSTNAME} (role=${NODE_ROLE})"
case "$NODE_ROLE" in
  pg_ha)
    if systemctl is-active --quiet patroni && [[ -f /etc/patroni/config.yml ]]; then
      if curl -sf "http://${NODE_IP}:8008/leader" >/dev/null 2>&1; then
        r2a_info "Node ${NODE_HOSTNAME} is current Patroni Leader; triggering graceful switchover..."
        patronictl -c /etc/patroni/config.yml switchover --force 2>/dev/null || true
        sleep 3
      fi
      systemctl stop patroni 2>/dev/null || true
    fi

    if command -v etcdctl >/dev/null 2>&1 && systemctl is-active --quiet etcd; then
      MEMBER_ID="$(ETCDCTL_API=3 etcdctl --endpoints="http://${NODE_IP}:2379" member list 2>/dev/null | awk -F', ' -v ip="${NODE_IP}" '$0 ~ ip {print $1; exit}' || true)"
      if [[ -n "$MEMBER_ID" ]]; then
        r2a_info "Removing Etcd Raft member ${MEMBER_ID} (${NODE_HOSTNAME})..."
        ETCDCTL_API=3 etcdctl --endpoints="http://${NODE_IP}:2379" member remove "$MEMBER_ID" 2>/dev/null || true
        sleep 1
      fi
    fi
    ;;

  pbx_telephony)
    if command -v fs_cli >/dev/null 2>&1 && systemctl is-active --quiet freeswitch; then
      r2a_info "Draining FreeSWITCH SIP sessions on ${NODE_HOSTNAME}..."
      fs_cli -x "fsctl pause" 2>/dev/null || true
      sleep 2
    fi
    ;;

  sbc_edge)
    r2a_info "Stopping Kamailio & RTPEngine edge node ${NODE_HOSTNAME}..."
    systemctl stop kamailio sbc-kamailio rtpengine ngcp-rtpengine-daemon 2>/dev/null || true
    ;;

  sbc_media)
    r2a_info "Stopping dedicated Media Relay server ${NODE_HOSTNAME}..."
    systemctl stop rtpengine ngcp-rtpengine-daemon 2>/dev/null || true
    ;;

  video_sfu)
    r2a_info "Stopping independent Video SFU server ${NODE_HOSTNAME}..."
    systemctl stop softswitch-video-egress softswitch-video-sip softswitch-video-sfu 2>/dev/null || true
    ;;

  storage_gluster)
    r2a_info "Stopping GlusterFS daemon on ${NODE_HOSTNAME}..."
    systemctl stop glusterd 2>/dev/null || true
    ;;

  *)
    r2a_info "Gracefully stopping standalone service node ${NODE_HOSTNAME}..."
    ;;
esac

r2a_step 2 2 "Executing clean factory teardown (85-destroy-node.sh) while preserving SSH trust"
exec bash "${SCRIPT_DIR}/85-destroy-node.sh"
