#!/usr/bin/env bash
# ==============================================================================
# 40-sbc-node.sh — Phase 4: Multi-Master SBC Edge Node (Kamailio DMQ + RTPEngine)
# Resolves Manual 19 Traps #7, #8, #9, #11, #13 (Zero-Trust :443, DMQ peers only,
# split usrloc db_mode=1 on primary vs db_mode=0 on peer SBCs).
# ==============================================================================
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
r2a_require_debian13

: "${NODE_IP:?NODE_IP is required}"
: "${SBC_ALL_IPS:?SBC_ALL_IPS (comma-separated) is required}"
: "${SBC_INDEX:?SBC_INDEX (1-based index of this SBC node) is required}"
: "${HA_CLUSTER_SECRET:?HA_CLUSTER_SECRET is required}"
: "${PBX_API_URL:?PBX_API_URL (e.g. https://192.168.10.36) is required}"
JWT_SHARED_SECRET="${SBC_JWT_SECRET:-}"

r2a_step 1 6 "Verifying isolated SBC DB credentials via local HAProxy :5000"
[[ -f /etc/softswitch/sbc-db-credentials ]] || r2a_fail "/etc/softswitch/sbc-db-credentials missing."
chmod 600 /etc/softswitch/sbc-db-credentials
# shellcheck disable=SC1091
source /etc/softswitch/sbc-db-credentials
PGPASSWORD="$DB_PASSWORD" psql -h 127.0.0.1 -p 5000 -U "$DB_USER" -d sbc_admin -tAc "SELECT 1" >/dev/null \
  || r2a_fail "sbc_admin DB check failed via 127.0.0.1:5000."
PGPASSWORD="$KAMAILIO_PASSWORD" psql -h 127.0.0.1 -p 5000 -U "$KAMAILIO_USER" -d kamailio -tAc "SELECT COUNT(*) FROM dispatcher" >/dev/null \
  || r2a_fail "kamailio DB check failed via 127.0.0.1:5000."

r2a_step 2 6 "Installing Multi-Master SBC packages (without softswitch-sbc-db)"
r2a_setup_ring2all_repo
apt-get install -y nodejs nginx certbot python3-certbot-nginx
apt-get install -y softswitch-sbc-api softswitch-sbc-admin softswitch-sbc-telephony

r2a_step 3 6 "Configuring Zero-Trust /etc/softswitch/sbc-api.env (HOST=127.0.0.1)"
r2a_set_env_kv /etc/softswitch/sbc-api.env "HOST" "127.0.0.1"
r2a_set_env_kv /etc/softswitch/sbc-api.env "DB_HOST" "127.0.0.1"
r2a_set_env_kv /etc/softswitch/sbc-api.env "DB_PORT" "5000"
r2a_set_env_kv /etc/softswitch/sbc-api.env "DB_SSL_MODE" "disable"
r2a_set_env_kv /etc/softswitch/sbc-api.env "HA_CLUSTER_SECRET" "$HA_CLUSTER_SECRET"
r2a_set_env_kv /etc/softswitch/sbc-api.env "PBX_API_URL" "$PBX_API_URL"
if [[ -n "$JWT_SHARED_SECRET" ]]; then
  r2a_set_env_kv /etc/softswitch/sbc-api.env "JWT_SECRET" "$JWT_SHARED_SECRET"
fi
if [[ -n "${INTERNAL_SERVICE_TOKEN:-}" ]]; then
  r2a_set_env_kv /etc/softswitch/sbc-api.env "INTERNAL_SERVICE_TOKEN" "$INTERNAL_SERVICE_TOKEN"
fi
chmod 600 /etc/softswitch/sbc-api.env

r2a_step 4 6 "Configuring Kamailio DMQ Active-Active Mesh & zero-collision usrloc db_mode split"
IFS=',' read -ra SBC_ARR <<< "$SBC_ALL_IPS"
PEER_NOTIFY_IP=""
for ip in "${SBC_ARR[@]}"; do
  ip="$(echo "$ip" | xargs)"
  if [[ "$ip" != "$NODE_IP" ]]; then
    PEER_NOTIFY_IP="$ip"
    break
  fi
done

if (( ${#SBC_ARR[@]} > 1 )) && [[ -n "$PEER_NOTIFY_IP" ]]; then
  if [[ "$SBC_INDEX" == "1" ]]; then
    USRLOC_DB_BLOCK=$(cat << 'EOB'
modparam("usrloc", "db_mode", 1)
modparam("usrloc", "db_check_update", 1)
modparam("usrloc", "db_ops_ruid", 1)
EOB
)
  else
    USRLOC_DB_BLOCK=$(cat << 'EOB'
modparam("usrloc", "db_mode", 0)
modparam("dialog", "db_mode", 0)
EOB
)
  fi

  cat << EOF > /etc/kamailio/sbc-ha.cfg
#!define WITH_DMQ
loadmodule "dmq_usrloc.so"

modparam("dmq", "server_address", "sip:${NODE_IP}:5090")
modparam("dmq", "notification_address", "sip:${PEER_NOTIFY_IP}:5090")
modparam("dmq", "multi_notify", 1)
modparam("dmq", "num_workers", 4)
modparam("dmq", "ping_interval", 15)

modparam("dialog", "enable_dmq", 1)
modparam("dmq_usrloc", "enable", 1)
modparam("dmq_usrloc", "sync", 1)
modparam("htable", "enable_dmq", 1)
${USRLOC_DB_BLOCK}
EOF
  chown root:softswitch /etc/kamailio/sbc-ha.cfg 2>/dev/null || chown root:root /etc/kamailio/sbc-ha.cfg
  chmod 664 /etc/kamailio/sbc-ha.cfg
fi

r2a_step 5 6 "Hardening SBC Border Firewall (Zero-Trust: close :3003, DMQ peers only, NMS SNMP/Agent)"
SBC_SET_NFT="$(echo "$SBC_ALL_IPS" | sed 's/,/, /g')"
NMS_SRC="${NMS_SERVER_IP:-$CLUSTER_SUBNET}"
if [[ -f /etc/nftables.conf ]]; then
  sed -i '/tcp dport 3003/d' /etc/nftables.conf
  sed -i "s|udp dport 5090 accept.*|ip saddr { ${SBC_SET_NFT} } udp dport 5090 accept comment \"Kamailio DMQ Peers Only\"|" /etc/nftables.conf
  if ! grep -q "tcp dport 9443 accept" /etc/nftables.conf; then
    sed -i "/tcp dport 22 accept/a \\        ip saddr ${NMS_SRC} udp dport 161 accept comment \"Ring2All NMS SNMPv3\"\n        ip saddr ${NMS_SRC} tcp dport 9443 accept comment \"Ring2All NMS Control Agent\"" /etc/nftables.conf
  fi
  nft -f /etc/nftables.conf
  systemctl enable --now nftables
fi

r2a_step 6 6 "Validating Kamailio configuration and restarting sbc-api, kamailio & nginx"
kamailio -c -f /etc/kamailio/kamailio.cfg
systemctl restart sbc-api kamailio nginx
r2a_wait_for_http_200 "https://127.0.0.1/api/health" 60 || r2a_fail "SBC API /api/health did not return 200."

r2a_ok "SBC Multi-Master node ${NODE_IP} (index=${SBC_INDEX}) active and hardened."
r2a_result "{\"service\":\"sbc_edge\",\"ip\":\"${NODE_IP}\",\"index\":${SBC_INDEX},\"dmq_peer\":\"${PEER_NOTIFY_IP}\"}"
