#!/usr/bin/env bash
# ==============================================================================
# 70-verify-cluster.sh — Phase 6B: Node-Scoped Horizontal Cluster Verification
# Runs Manual 19 validation checks matching NODE_ROLE and returns JSON via @@R2A_RESULT.
# ==============================================================================
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
NODE_ROLE="${NODE_ROLE:-unknown}"
CHECKS_JSON=()
PASSED=0
FAILED=0
CLUSTER_CMD=""
CLUSTER_OUTPUT=""

add_check() {
  local name="$1"
  local ok="$2"
  local detail="$3"
  detail="$(echo "$detail" | tr '\n' ' ' | sed 's/"/\\"/g' | cut -c1-180)"
  if [[ "$ok" == "true" ]]; then
    PASSED=$((PASSED + 1))
  else
    FAILED=$((FAILED + 1))
  fi
  CHECKS_JSON+=("{\"name\":\"${name}\",\"ok\":${ok},\"detail\":\"${detail}\"}")
}

r2a_step 1 2 "Running role-specific verification checks for ${NODE_ROLE}"
case "$NODE_ROLE" in
  pg_ha)
    CLUSTER_CMD="patronictl -c /etc/patroni/config.yml list"
    if CLUSTER_OUTPUT="$(patronictl -c /etc/patroni/config.yml list 2>/dev/null)"; then
      OUT="$(echo "$CLUSTER_OUTPUT" | grep -E 'Leader|Replica' | wc -l)"
      add_check "patroni_cluster" "true" "Patroni active members: ${OUT}"
      echo "$CLUSTER_OUTPUT"
    else
      CLUSTER_OUTPUT=""
      add_check "patroni_cluster" "false" "patronictl list failed"
    fi
    if systemctl is-active --quiet etcd; then
      add_check "etcd_service" "true" "etcd active"
    else
      add_check "etcd_service" "false" "etcd inactive"
    fi
    ;;

  storage_gluster)
    CLUSTER_CMD="gluster peer status && gluster volume list"
    if systemctl is-active --quiet glusterd; then
      STARTED="$(gluster volume list 2>/dev/null | wc -l)"
      CLUSTER_OUTPUT="$(gluster peer status 2>/dev/null || true)"$'\n'"--- Volumes ---"$'\n'"$(gluster volume list 2>/dev/null || true)"
      add_check "gluster_volumes" "true" "glusterd active, volumes=${STARTED}"
      echo "$CLUSTER_OUTPUT"
    else
      add_check "gluster_volumes" "false" "glusterd inactive"
    fi
    ;;

  pbx_admin)
    CLUSTER_CMD="systemctl is-active softswitch-api softswitch-monitoring-api haproxy nginx && df -hT /var/www/softswitch/uploads /var/lib/softswitch/recordings /usr/share/softswitch/sounds/music"
    CODE="$(curl -sk -o /dev/null -w '%{http_code}' https://127.0.0.1/api/health || echo 000)"
    if [[ "$CODE" == "200" ]]; then
      add_check "pbx_api_health" "true" "HTTPS /api/health returned 200"
    else
      add_check "pbx_api_health" "false" "HTTPS /api/health returned ${CODE}"
    fi
    if mountpoint -q /var/www/softswitch/uploads && mountpoint -q /var/lib/softswitch/recordings && mountpoint -q /usr/share/softswitch/sounds/music; then
      STOR_DRIVER="$(grep -E '^STORAGE_MODE=' /etc/softswitch/storage.env 2>/dev/null | cut -d= -f2- || echo glusterfs_replica3)"
      if [[ -L /usr/share/freeswitch/recordings && -L /var/lib/freeswitch/recordings && -L /usr/share/freeswitch/sounds/music ]]; then
        add_check "shared_storage_mounts" "true" "ss-uploads, ss-recordings & ss-music mounted & symlinked (${STOR_DRIVER})"
      else
        add_check "shared_storage_mounts" "false" "Shared storage mounted (${STOR_DRIVER}) but MOH/recordings symlinks missing on pbx_admin"
      fi
    else
      add_check "shared_storage_mounts" "false" "Missing shared storage mount (ss-uploads/ss-recordings/ss-music) on pbx_admin"
    fi
    SVC_OUT="$(for s in softswitch-api softswitch-monitoring-api haproxy nginx; do printf '%-26s %s\n' "$s" "$(systemctl is-active "$s" 2>/dev/null || echo inactive)"; done)"
    MNT_OUT="$(df -hT /var/www/softswitch/uploads /var/lib/softswitch/recordings /usr/share/softswitch/sounds/music 2>/dev/null || true)"
    CLUSTER_OUTPUT="${SVC_OUT}"$'\n'"--- Shared Cluster Storage Mounts ---"$'\n'"${MNT_OUT}"
    ;;

  pbx_portal_edge)
    CLUSTER_CMD="curl -skI https://127.0.0.1/connect/ && curl -sk https://127.0.0.1/api/health"
    PORTAL_CODE="$(curl -sk -o /dev/null -w '%{http_code}' https://127.0.0.1/connect/ || echo 000)"
    API_CODE="$(curl -sk -o /dev/null -w '%{http_code}' https://127.0.0.1/api/health || echo 000)"
    add_check "connect_portal_https" "$( [[ "$PORTAL_CODE" == "200" ]] && echo true || echo false )" "HTTPS /connect/ returned ${PORTAL_CODE}"
    add_check "pbx_api_upstream_proxy" "$( [[ "$API_CODE" == "200" ]] && echo true || echo false )" "Proxied /api/health returned ${API_CODE}"
    CLUSTER_OUTPUT="GET /connect/ -> HTTP ${PORTAL_CODE}"$'\n'"GET /api/health (upstream pbx_api_pool) -> HTTP ${API_CODE}"
    ;;

  pbx_switchboard_edge)
    CLUSTER_CMD="curl -skI https://127.0.0.1/switchboard/ && curl -sk https://127.0.0.1/api/health"
    SB_CODE="$(curl -sk -o /dev/null -w '%{http_code}' https://127.0.0.1/switchboard/ || echo 000)"
    API_CODE="$(curl -sk -o /dev/null -w '%{http_code}' https://127.0.0.1/api/health || echo 000)"
    add_check "switchboard_https" "$( [[ "$SB_CODE" == "200" ]] && echo true || echo false )" "HTTPS /switchboard/ returned ${SB_CODE}"
    add_check "pbx_api_upstream_proxy" "$( [[ "$API_CODE" == "200" ]] && echo true || echo false )" "Proxied /api/health returned ${API_CODE}"
    CLUSTER_OUTPUT="GET /switchboard/ -> HTTP ${SB_CODE}"$'\n'"GET /api/health (upstream pbx_api_pool) -> HTTP ${API_CODE}"
    ;;

  pbx_telephony)
    CLUSTER_CMD="fs_cli -x 'sofia status'"
    CLUSTER_OUTPUT="$(fs_cli -x 'sofia status' 2>/dev/null | head -n 30 || true)"
    SOFIA="$(echo "$CLUSTER_OUTPUT" | grep -c 'RUNNING' || echo 0)"
    if (( SOFIA >= 2 )); then
      add_check "telephony_sip_profiles" "true" "${SOFIA} SIP profiles RUNNING"
    else
      add_check "telephony_sip_profiles" "false" "Expected >=2 SIP profiles RUNNING, found ${SOFIA}"
    fi
    if mountpoint -q /var/lib/softswitch/recordings && mountpoint -q /usr/share/softswitch/sounds/music; then
      STOR_DRIVER="$(grep -E '^STORAGE_MODE=' /etc/softswitch/storage.env 2>/dev/null | cut -d= -f2- || echo glusterfs_replica3)"
      add_check "shared_storage_mounts" "true" "ss-recordings & ss-music mounted (${STOR_DRIVER})"
    else
      add_check "shared_storage_mounts" "false" "Missing shared storage mount on pbx_telephony"
    fi
    ;;

  sbc_edge)
    CLUSTER_CMD="kamcmd dmq.list_nodes && kamcmd dispatcher.list"
    CODE="$(curl -sk -o /dev/null -w '%{http_code}' https://127.0.0.1/api/health || echo 000)"
    if [[ "$CODE" == "200" ]]; then
      add_check "sbc_api_health" "true" "HTTPS /api/health returned 200"
    else
      add_check "sbc_api_health" "false" "HTTPS /api/health returned ${CODE}"
    fi
    DISP_OUT="$(kamcmd dispatcher.list 2>/dev/null || true)"
    DMQ_OUT="$(kamcmd dmq.list_nodes 2>/dev/null || true)"
    CLUSTER_OUTPUT="--- DMQ Nodes ---"$'\n'"${DMQ_OUT}"$'\n'"--- Dispatchers ---"$'\n'"$(echo "$DISP_OUT" | head -n 30)"
    DISP="$(echo "$DISP_OUT" | grep -c 'FLAGS: AP' || echo 0)"
    if (( DISP >= 1 )); then
      add_check "sbc_dispatcher" "true" "${DISP} active probing Telephony destinations"
    else
      add_check "sbc_dispatcher" "false" "No AP destinations in dispatcher.list"
    fi
    DMQ="$(echo "$DMQ_OUT" | grep -c 'active' || echo 0)"
    add_check "sbc_dmq" "$( (( DMQ >= 1 )) && echo true || echo false )" "DMQ active nodes: ${DMQ}"
    ;;

  sbc_media)
    CLUSTER_CMD="systemctl is-active ngcp-rtpengine-daemon && grep -E 'listen-ng|port-min|port-max|table' /etc/rtpengine/rtpengine.conf"
    if systemctl is-active --quiet ngcp-rtpengine-daemon; then
      add_check "media_relay_daemon" "true" "ngcp-rtpengine-daemon active"
    else
      add_check "media_relay_daemon" "false" "ngcp-rtpengine-daemon inactive"
    fi
    MEDIA_BIND="$(grep -E '^listen-ng' /etc/rtpengine/rtpengine.conf 2>/dev/null | head -n1 | cut -d= -f2- | xargs || echo '127.0.0.1:2223')"
    MEDIA_HOST="${MEDIA_BIND%:*}"
    MEDIA_PORT="${MEDIA_BIND##*:}"
    NG_CHECK="$(python3 - "${MEDIA_HOST}" "${MEDIA_PORT}" << 'PYEOF' 2>/dev/null || true
import socket, sys
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.settimeout(2.5)
s.sendto(b"verify_ping d7:command4:pinge", (sys.argv[1], int(sys.argv[2])))
data, _ = s.recvfrom(512)
s.close()
print(data.decode("utf-8", errors="ignore").strip())
PYEOF
)"
    if echo "$NG_CHECK" | grep -q "pong"; then
      add_check "media_relay_ng_ping" "true" "NG UDP ${MEDIA_HOST}:${MEDIA_PORT} responded pong"
    else
      add_check "media_relay_ng_ping" "false" "NG UDP ${MEDIA_HOST}:${MEDIA_PORT} did not respond pong"
    fi
    CLUSTER_OUTPUT="$(systemctl is-active ngcp-rtpengine-daemon 2>/dev/null || echo inactive)"$'\n'"NG Ping: ${NG_CHECK:-timeout}"$'\n'"$(grep -E '^(listen-ng|port-min|port-max|table)' /etc/rtpengine/rtpengine.conf 2>/dev/null || true)"
    ;;

  video_sfu)
    CLUSTER_CMD="systemctl is-active softswitch-video-sfu softswitch-video-sip softswitch-video-egress redis-server && ss -tlnp | grep -E '7880|7881|5070'"
    if systemctl is-active --quiet softswitch-video-sfu; then
      add_check "video_sfu_core" "true" "softswitch-video-sfu active"
    else
      add_check "video_sfu_core" "false" "softswitch-video-sfu inactive"
    fi
    if systemctl is-active --quiet redis-server; then
      add_check "video_local_redis" "true" "local redis-server active"
    else
      add_check "video_local_redis" "false" "local redis-server inactive"
    fi
    if ss -tln 2>/dev/null | grep -q ':7880 '; then
      add_check "video_sfu_signaling" "true" "TCP :7880 signaling listening"
    else
      add_check "video_sfu_signaling" "false" "TCP :7880 signaling not listening"
    fi
    CLUSTER_OUTPUT="$(for s in softswitch-video-sfu softswitch-video-sip softswitch-video-egress redis-server; do printf '%-28s %s\n' "$s" "$(systemctl is-active "$s" 2>/dev/null || echo inactive)"; done)"
    ;;

  bss_admin)
    CLUSTER_CMD="systemctl is-active softswitch-bss-api haproxy nginx && curl -sk https://127.0.0.1/api/health"
    CODE="$(curl -sk -o /dev/null -w '%{http_code}' https://127.0.0.1/api/health || echo 000)"
    add_check "bss_api_health" "$( [[ "$CODE" == "200" ]] && echo true || echo false )" "HTTPS /api/health returned ${CODE}"
    CLUSTER_OUTPUT="$(for s in softswitch-bss-api haproxy nginx; do printf '%-24s %s\n' "$s" "$(systemctl is-active "$s" 2>/dev/null || echo inactive)"; done)"
    ;;

  bss_client)
    CLUSTER_CMD="curl -skI https://127.0.0.1/ && curl -sk https://127.0.0.1/api/health && curl -skI https://127.0.0.1/api/customers"
    SPA_CODE="$(curl -sk -o /dev/null -w '%{http_code}' https://127.0.0.1/ || echo 000)"
    API_CODE="$(curl -sk -o /dev/null -w '%{http_code}' https://127.0.0.1/api/health || echo 000)"
    CODE="$(curl -sk -o /dev/null -w '%{http_code}' https://127.0.0.1/api/customers || echo 000)"
    add_check "bss_client_spa_https" "$( [[ "$SPA_CODE" == "200" ]] && echo true || echo false )" "HTTPS / returned HTTP ${SPA_CODE}"
    add_check "bss_client_api_proxy" "$( [[ "$API_CODE" == "200" ]] && echo true || echo false )" "Proxied /api/health returned HTTP ${API_CODE}"
    add_check "bss_client_perimeter_403" "$( [[ "$CODE" == "403" ]] && echo true || echo false )" "/api/customers perimeter returned HTTP ${CODE}"
    CLUSTER_OUTPUT="GET / -> HTTP ${SPA_CODE}"$'\n'"GET /api/health (upstream bss_api_pool) -> HTTP ${API_CODE}"$'\n'"GET /api/customers (perimeter guard) -> HTTP ${CODE}"
    ;;

  *)
    add_check "node_reachable" "true" "Generic node verification passed"
    ;;
esac

r2a_step 2 2 "Compiling verification summary"
ARR_STR="$(IFS=','; echo "${CHECKS_JSON[*]}")"
CLUSTER_OUTPUT_B64=""
if [[ -n "$CLUSTER_OUTPUT" ]]; then
  CLUSTER_OUTPUT_B64="$(printf '%s' "$CLUSTER_OUTPUT" | base64 -w 0 2>/dev/null || printf '%s' "$CLUSTER_OUTPUT" | base64 | tr -d '\n')"
fi
CLUSTER_CMD_SAFE="$(echo "$CLUSTER_CMD" | sed 's/"/\\"/g')"
r2a_ok "Verification complete for ${NODE_ROLE}: passed=${PASSED}, failed=${FAILED}."
r2a_result "{\"role\":\"${NODE_ROLE}\",\"passed\":${PASSED},\"failed\":${FAILED},\"cluster_cmd\":\"${CLUSTER_CMD_SAFE}\",\"cluster_output_b64\":\"${CLUSTER_OUTPUT_B64}\",\"checks\":[${ARR_STR}]}"
(( FAILED == 0 ))
