#!/usr/bin/env bash
# ==============================================================================
# 32-pbx-telephony.sh — Phase 3B: Headless FreeSWITCH 1.11+ Telephony Core Node
# No Nginx installed. Mounts ss-recordings + ss-music (GID 2000), enforces Profile B FW.
# ==============================================================================
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=lib/common.sh
source "${SCRIPT_DIR}/lib/common.sh"
# shellcheck source=lib/storage-mount.sh
source "${SCRIPT_DIR}/lib/storage-mount.sh"

r2a_load_env
r2a_require_root
r2a_require_debian13
r2a_sync_clock

STORAGE_MODE="${STORAGE_MODE:-glusterfs_replica3}"
if [[ "$STORAGE_MODE" == "glusterfs_replica3" ]]; then
  : "${FS_NODE_HOSTNAMES:?FS_NODE_HOSTNAMES is required when STORAGE_MODE=glusterfs_replica3}"
fi
: "${CLUSTER_SUBNET:?CLUSTER_SUBNET is required}"
PBX_ADMIN_IPS="${PBX_ADMIN_IPS:-${PBX_ADMIN_IP:-}}"
[[ -n "$PBX_ADMIN_IPS" ]] || r2a_fail "PBX_ADMIN_IPS or PBX_ADMIN_IP is required."

r2a_step 1 5 "Verifying isolated PBX DB credentials via local HAProxy :5000"
[[ -f /etc/softswitch/pbx-db-credentials ]] || r2a_fail "/etc/softswitch/pbx-db-credentials missing."
chmod 600 /etc/softswitch/pbx-db-credentials
# shellcheck disable=SC1091
source /etc/softswitch/pbx-db-credentials
PGPASSWORD="$DB_PASSWORD" psql -h 127.0.0.1 -p 5000 -U "$DB_USER" -d ss_telephony -tAc "SELECT 1" >/dev/null \
  || r2a_fail "ss_telephony DB check failed via 127.0.0.1:5000."

r2a_step 2 5 "Mounting cluster shared storage (${STORAGE_MODE}: ss-recordings & ss-music, GID 2000)"
r2a_mount_cluster_storage \
  "ss-recordings:/var/lib/softswitch/recordings" \
  "ss-music:/usr/share/softswitch/sounds/music"

r2a_step 3 5 "Installing headless softswitch-pbx-telephony, music, and voiceguides (no Nginx)"
r2a_setup_ring2all_repo
apt-get install -y -o Dpkg::Options::="--force-overwrite" \
  softswitch-pbx-telephony softswitch-pbx-music \
  softswitch-pbx-voiceguide-emma softswitch-pbx-voiceguide-paloma

if [[ -f /etc/odbc.ini ]]; then
  sed -i 's/SSLMode = prefer/SSLMode = disable/g' /etc/odbc.ini
fi

if id -u freeswitch >/dev/null 2>&1; then
  usermod -aG "${MEDIA_GROUP:-r2a-media}" freeswitch || true
fi
mkdir -p /var/lib/softswitch/recordings/domains /usr/share/softswitch/sounds/music
chgrp -R "${MEDIA_GID:-2000}" /var/lib/softswitch/recordings /usr/share/softswitch/sounds/music || true
chmod 2775 /var/lib/softswitch/recordings /var/lib/softswitch/recordings/domains /usr/share/softswitch/sounds/music || true

# Symlink FreeSWITCH recording & music paths to shared cluster storage (Manual 19 Trap #14)
for rec_link in /var/lib/freeswitch/recordings /usr/share/freeswitch/recordings; do
  if [[ -d "$rec_link" && ! -L "$rec_link" ]]; then
    cp -an "$rec_link/." /var/lib/softswitch/recordings/ 2>/dev/null || true
    rm -rf "$rec_link"
  fi
  mkdir -p "$(dirname "$rec_link")"
  ln -sfn /var/lib/softswitch/recordings "$rec_link"
done
if [[ -d /opt/softswitch/telephony/sounds/music/default && ! -d /usr/share/softswitch/sounds/music/default ]]; then
  cp -aL /opt/softswitch/telephony/sounds/music/default /usr/share/softswitch/sounds/music/default 2>/dev/null || true
fi
if [[ -d /usr/share/freeswitch/sounds/music && ! -L /usr/share/freeswitch/sounds/music ]]; then
  cp -aLn /usr/share/freeswitch/sounds/music/. /usr/share/softswitch/sounds/music/ 2>/dev/null || true
  rm -rf /usr/share/freeswitch/sounds/music
fi
mkdir -p /usr/share/freeswitch/sounds
ln -sfn /usr/share/softswitch/sounds/music /usr/share/freeswitch/sounds/music
chgrp -R "${MEDIA_GID:-2000}" /usr/share/softswitch/sounds/music || true
chmod 2775 /usr/share/softswitch/sounds/music || true

r2a_step 4 5 "Applying Telephony Plane firewall (nftables Profile B + NMS SNMPv3/Agent)"
NMS_SRC="${NMS_SERVER_IP:-$CLUSTER_SUBNET}"
ADMIN_NFT_SET=""
IFS=',' read -ra _ADMIN_ARR <<< "$PBX_ADMIN_IPS"
for aip in "${_ADMIN_ARR[@]}"; do
  aip="$(echo "$aip" | xargs)"
  [[ -z "$aip" ]] && continue
  ADMIN_NFT_SET+="${aip}, "
done
ADMIN_NFT_SET="${ADMIN_NFT_SET%, }"
cat << EOF > /etc/nftables.conf
#!/usr/sbin/nft -f

flush ruleset

table inet filter {
    chain input {
        type filter hook input priority 0; policy drop;

        iif "lo" accept
        ct state established,related accept
        ct state invalid drop

        ip protocol icmp accept
        tcp dport 22 accept

        # Ring2All NMS SNMPv3 (161/udp) & Native Node Control API (9443/tcp)
        ip saddr ${NMS_SRC} udp dport 161 accept
        ip saddr ${NMS_SRC} tcp dport 9443 accept

        # SIP Signaling & RTP Media
        udp dport { 5060, 5080 } accept
        tcp dport { 5060, 5080, 5061 } accept
        udp dport 16384-32768 accept
        tcp dport 7443 accept

        # Native ESL (8021) strictly from PBX Control Plane pool & internal subnet
        ip saddr { ${ADMIN_NFT_SET} } tcp dport 8021 accept
        ip saddr ${CLUSTER_SUBNET} accept
    }
    chain forward { type filter hook forward priority 0; policy drop; }
    chain output  { type filter hook output priority 0; policy accept; }
}
EOF
systemctl enable --now nftables
nft -f /etc/nftables.conf

r2a_step 5 5 "Restarting Telephony engine and verifying SIP profiles"
systemctl restart freeswitch
sleep 4
SOFIA_OUT="$(fs_cli -x 'sofia status' 2>/dev/null || true)"
echo "$SOFIA_OUT"
if ! echo "$SOFIA_OUT" | grep -q "RUNNING"; then
  r2a_fail "Telephony SIP profiles are not RUNNING."
fi

r2a_ok "Telephony node deployed and running."
r2a_result "{\"service\":\"pbx_telephony\",\"sofia\":\"running\"}"
