#!/usr/bin/env bash
# ==============================================================================
# 42-sbc-media-node.sh — Optional Dedicated Media Relay Server (Independent N+1)
# Installs standalone RTP/SRTP/WebRTC media relay daemon on Debian 13, tunes
# kernel UDP buffers, binds NG control protocol (:2223) strictly to SBC Edge IPs,
# and verifies local NG ping health. Nodes operate independently; Ring2All SBC
# distributes media load across all registered active servers.
# ==============================================================================
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_EDGE_IPS="${SBC_EDGE_IPS:-}"
CLUSTER_SUBNET="${CLUSTER_SUBNET:-192.168.0.0/16}"
NMS_SRC="${NMS_SERVER_IP:-$CLUSTER_SUBNET}"
RTP_PORT_MIN="${RTP_PORT_MIN:-20000}"
RTP_PORT_MAX="${RTP_PORT_MAX:-40000}"
MEDIA_NG_PORT="${MEDIA_NG_PORT:-2223}"
export DEBIAN_FRONTEND=noninteractive

r2a_step 1 5 "Installing Media Relay engine packages and nftables on Debian 13"
r2a_setup_ring2all_repo
apt-get install -y ngcp-rtpengine-daemon ngcp-rtpengine-utils nftables python3

r2a_step 2 5 "Applying carrier UDP media kernel tuning (/etc/sysctl.d/99-softswitch-media-relay.conf)"
cat << 'EOF' > /etc/sysctl.d/99-softswitch-media-relay.conf
# Carrier RTP/SRTP UDP socket buffer tuning for dedicated Media Relay nodes
net.core.rmem_max = 67108864
net.core.wmem_max = 67108864
net.core.rmem_default = 33554432
net.core.wmem_default = 33554432
net.core.netdev_max_backlog = 100000
net.ipv4.udp_rmem_min = 16384
net.ipv4.udp_wmem_min = 16384
fs.file-max = 2097152
EOF
sysctl --system >/dev/null 2>&1 || true

r2a_step 3 5 "Configuring dedicated Media Relay daemon (/etc/rtpengine/rtpengine.conf)"
mkdir -p /etc/rtpengine /var/spool/rtpengine
if [[ -f /etc/rtpengine/rtpengine.conf && ! -f /etc/rtpengine/rtpengine.conf.orig ]]; then
  cp /etc/rtpengine/rtpengine.conf /etc/rtpengine/rtpengine.conf.orig
fi

RTP_TABLE=-1
if modprobe -q xt_RTPENGINE 2>/dev/null; then
  RTP_TABLE=0
fi

cat << EOF > /etc/rtpengine/rtpengine.conf
[rtpengine]
table = ${RTP_TABLE}
interfaces-config = interface
templates = templates
listen-ng = ${NODE_IP}:${MEDIA_NG_PORT}
listen-http = 127.0.0.1:2225
listen-cli = 127.0.0.1:2224
timeout = 60
silent-timeout = 3600
tos = 184
port-min = ${RTP_PORT_MIN}
port-max = ${RTP_PORT_MAX}
recording-dir = /var/spool/rtpengine
recording-method = proc
transcode-config = transcode

[example-transcode-1]
source = opus
destination = PCMA

[example-transcode-2]
source = PCMA
destination = opus

[templates]
WebRTC = transport-protocol=UDP/TLS/RTP/SAVPF ICE=force trickle-ICE rtcp-mux=[offer require] no-rtcp-attribute SDES=off generate-mid bundle=[require]

[interface-default]
address = ${NODE_IP}

[interface-ext]
address = ${NODE_IP}

[interface-int]
address = ${NODE_IP}
EOF
chmod 640 /etc/rtpengine/rtpengine.conf

r2a_step 4 5 "Enforcing Media Relay Zero-Trust firewall (NG :${MEDIA_NG_PORT} restricted to SBC Edge peers)"
SBC_ALLOW_RULE="ip saddr ${CLUSTER_SUBNET} udp dport ${MEDIA_NG_PORT} accept comment \"SBC Edge NG Control\""
if [[ -n "$SBC_EDGE_IPS" ]]; then
  SBC_SET_NFT="$(echo "$SBC_EDGE_IPS" | sed 's/,/, /g')"
  SBC_ALLOW_RULE="ip saddr { ${SBC_SET_NFT} } udp dport ${MEDIA_NG_PORT} accept comment \"SBC Edge NG Control Only\""
fi

cat << EOF > /etc/nftables.conf
#!/usr/sbin/nft -f

flush ruleset

table inet filter {
    chain input {
        type filter hook input priority 0; policy drop;
        iifname "lo" accept
        ct state established,related accept
        ip protocol icmp accept
        tcp dport 22 accept comment "SSH Management"
        ip saddr ${NMS_SRC} udp dport 161 accept comment "Ring2All NMS SNMPv3"
        ip saddr ${NMS_SRC} tcp dport 9443 accept comment "Ring2All NMS Control Agent"
        ${SBC_ALLOW_RULE}
        udp dport ${RTP_PORT_MIN}-${RTP_PORT_MAX} accept comment "RTP/SRTP/WebRTC Media Relay"
    }
    chain forward {
        type filter hook forward priority 0; policy drop;
    }
    chain output {
        type filter hook output priority 0; policy accept;
    }
}
EOF
nft -f /etc/nftables.conf
systemctl enable --now nftables

r2a_step 5 5 "Starting Media Relay service and validating NG UDP :${MEDIA_NG_PORT} ping"
systemctl enable ngcp-rtpengine-daemon
systemctl restart ngcp-rtpengine-daemon
sleep 2
systemctl is-active --quiet ngcp-rtpengine-daemon || r2a_fail "ngcp-rtpengine-daemon failed to start."

NG_PONG="$(python3 - "${NODE_IP}" "${MEDIA_NG_PORT}" << 'PYEOF'
import socket, sys
host, port = sys.argv[1], int(sys.argv[2])
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.settimeout(3.0)
s.sendto(b"nms_ping d7:command4:pinge", (host, port))
data, _ = s.recvfrom(512)
s.close()
print(data.decode("utf-8", errors="ignore").strip())
PYEOF
)" || r2a_fail "Media Relay NG UDP ping failed on ${NODE_IP}:${MEDIA_NG_PORT}"

echo "$NG_PONG" | grep -q "pong" || r2a_fail "Unexpected NG ping response: ${NG_PONG}"

r2a_ok "Independent Media Relay server ${NODE_IP}:${MEDIA_NG_PORT} active (kernel_table=${RTP_TABLE}, rtp=${RTP_PORT_MIN}-${RTP_PORT_MAX})."
r2a_result "{\"service\":\"sbc_media\",\"ip\":\"${NODE_IP}\",\"ng_port\":${MEDIA_NG_PORT},\"kernel_table\":${RTP_TABLE},\"ng_ping\":\"pong\"}"
