#!/usr/bin/env bash
# ==============================================================================
# 45-video-sfu-node.sh — Optional Independent Video SFU Server (Ring2All Video)
# Installs softswitch-video-all (SFU, SIP Bridge, Egress) + local Redis on
# Debian 13. Each server runs 100% independently with zero inter-node mesh
# coupling; Ring2All PBX balances rooms via smart load-based placement and
# pins participants to their assigned server.
# ==============================================================================
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}"
: "${VIDEO_API_KEY:?VIDEO_API_KEY is required}"
: "${VIDEO_API_SECRET:?VIDEO_API_SECRET is required}"
TELEPHONY_NODE_IPS="${TELEPHONY_NODE_IPS:-}"
CLUSTER_SUBNET="${CLUSTER_SUBNET:-192.168.0.0/16}"
NMS_SRC="${NMS_SERVER_IP:-$CLUSTER_SUBNET}"
VIDEO_WS_PORT="${VIDEO_WS_PORT:-7880}"
VIDEO_RTC_PORT="${VIDEO_RTC_PORT:-7881}"
VIDEO_SIP_PORT="${VIDEO_SIP_PORT:-5070}"
VIDEO_MAX_PARTICIPANTS="${VIDEO_MAX_PARTICIPANTS:-150}"
export DEBIAN_FRONTEND=noninteractive

r2a_step 1 5 "Installing Ring2All Video SFU suite (softswitch-video-all, redis-server, nftables)"
r2a_setup_ring2all_repo
apt-get install -y redis-server redis-tools nftables softswitch-video-all

r2a_step 2 5 "Ensuring local Redis (127.0.0.1:6379) for standalone server autonomy"
systemctl enable --now redis-server
redis-cli -h 127.0.0.1 -p 6379 ping | grep -qi "PONG" || r2a_fail "Local redis-server failed health check."

r2a_step 3 5 "Configuring SFU, SIP Bridge, and Egress with vaulted cluster credentials"
mkdir -p /etc/softswitch/video /var/log/softswitch/video
printf '%s\n' "${VIDEO_API_SECRET}" > /etc/softswitch/video/.api_secret
chmod 600 /etc/softswitch/video/.api_secret

cat << EOF > /etc/softswitch/video/livekit.yaml
# Auto-generated by Ring2All NMS (Independent Video SFU Server)
port: ${VIDEO_WS_PORT}
bind_addresses:
  - "0.0.0.0"

rtc:
  tcp_port: ${VIDEO_RTC_PORT}
  port_range_start: 52000
  port_range_end: 60000
  use_external_ip: true
  enable_loopback_candidate: false

keys:
  ${VIDEO_API_KEY}: "${VIDEO_API_SECRET}"

logging:
  json: false
  level: info

room:
  max_participants: ${VIDEO_MAX_PARTICIPANTS}
  empty_timeout: 300
  departure_timeout: 20

turn:
  enabled: false
  domain: ""
  cert_file: ""
  key_file: ""
  tls_port: 5349
  udp_port: 3478

redis:
  address: 127.0.0.1:6379
  db: 0
EOF

cat << EOF > /etc/softswitch/video/sip.yaml
api_key: "${VIDEO_API_KEY}"
api_secret: "${VIDEO_API_SECRET}"
ws_url: "ws://127.0.0.1:${VIDEO_WS_PORT}"

redis:
  address: "127.0.0.1:6379"
  db: 0

sip_port: ${VIDEO_SIP_PORT}
rtp_port: "50000-51999"
use_external_ip: true

logging:
  level: info
EOF

cat << EOF > /etc/softswitch/video/egress.yaml
api_key: "${VIDEO_API_KEY}"
api_secret: "${VIDEO_API_SECRET}"
ws_url: "ws://127.0.0.1:${VIDEO_WS_PORT}"

redis:
  address: "127.0.0.1:6379"
  db: 0

logging:
  level: info
EOF

chown -R softswitch-video:softswitch-video /etc/softswitch/video /var/log/softswitch/video
chmod 750 /etc/softswitch/video
chmod 640 /etc/softswitch/video/*.yaml

r2a_step 4 5 "Enforcing Video SFU perimeter firewall (SIP Bridge :${VIDEO_SIP_PORT} scoped to Telephony)"
SIP_ALLOW_RULE="ip saddr ${CLUSTER_SUBNET} udp dport ${VIDEO_SIP_PORT} accept comment \"Telephony SIP Bridge\""
SIP_ALLOW_TCP="ip saddr ${CLUSTER_SUBNET} tcp dport ${VIDEO_SIP_PORT} accept comment \"Telephony SIP Bridge TCP\""
if [[ -n "$TELEPHONY_NODE_IPS" ]]; then
  TEL_SET_NFT="$(echo "$TELEPHONY_NODE_IPS" | sed 's/,/, /g')"
  SIP_ALLOW_RULE="ip saddr { ${TEL_SET_NFT} } udp dport ${VIDEO_SIP_PORT} accept comment \"Telephony SIP Bridge Only\""
  SIP_ALLOW_TCP="ip saddr { ${TEL_SET_NFT} } tcp dport ${VIDEO_SIP_PORT} accept comment \"Telephony SIP Bridge TCP 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"
        tcp dport { 80, 443, ${VIDEO_WS_PORT}, ${VIDEO_RTC_PORT} } accept comment "Video SFU WebRTC/WSS Signaling"
        ${SIP_ALLOW_RULE}
        ${SIP_ALLOW_TCP}
        udp dport 50000-60000 accept comment "Video SFU WebRTC & SIP Media"
    }
    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 Video SFU, SIP Bridge, and Egress services and verifying :${VIDEO_WS_PORT}"
systemctl daemon-reload
systemctl enable softswitch-video-sfu softswitch-video-sip softswitch-video-egress
systemctl restart softswitch-video-sfu
sleep 2
systemctl restart softswitch-video-sip softswitch-video-egress || true

systemctl is-active --quiet softswitch-video-sfu || r2a_fail "softswitch-video-sfu service is not active."
r2a_wait_for_tcp "127.0.0.1" "${VIDEO_WS_PORT}" 30 || r2a_fail "Video SFU signaling port :${VIDEO_WS_PORT} did not open."

r2a_ok "Independent Video SFU server ${NODE_IP} active (ws=:${VIDEO_WS_PORT}, rtc=:${VIDEO_RTC_PORT}, sip=:${VIDEO_SIP_PORT})."
r2a_result "{\"service\":\"video_sfu\",\"ip\":\"${NODE_IP}\",\"ws_port\":${VIDEO_WS_PORT},\"rtc_port\":${VIDEO_RTC_PORT},\"sip_port\":${VIDEO_SIP_PORT}}"
