#!/usr/bin/env bash
# ==============================================================================
# 34-pbx-portal-edge.sh — Dedicated Ring2All Connect (User Portal) Edge Server
# Stateless web front-end (1..N) serving /connect/ over HTTPS with automatic
# Nginx upstream load-balancing & failover across all PBX Control Plane nodes.
# ==============================================================================
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
r2a_sync_clock

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 4 "Installing Nginx, nftables, and softswitch-pbx-portal (Ring2All Connect)"
r2a_setup_ring2all_repo
apt-get install -y nginx nftables curl gnupg2 ca-certificates openssl certbot python3-certbot-nginx
PRIMARY_ADMIN_IP="$(echo "$PBX_ADMIN_IPS" | cut -d',' -f1 | xargs)"
mkdir -p /etc/softswitch
echo "$PRIMARY_ADMIN_IP" > /etc/softswitch/pbx-api-host
ADMIN_SERVER_IP="$PRIMARY_ADMIN_IP" apt-get install -y softswitch-pbx-portal

r2a_step 2 4 "Configuring HTTPS Nginx upstream load-balancer across PBX Admin pool"
mkdir -p /etc/nginx/ssl /etc/nginx/sites-available /etc/nginx/sites-enabled /etc/nginx/snippets
if [[ -n "${PBX_PUBLIC_BRANDING_API_KEY:-}" ]]; then
  printf 'proxy_set_header x-branding-key "%s";\n' "$PBX_PUBLIC_BRANDING_API_KEY" > /etc/nginx/snippets/softswitch-branding-key.conf
  chmod 644 /etc/nginx/snippets/softswitch-branding-key.conf
elif [[ ! -f /etc/nginx/snippets/softswitch-branding-key.conf ]]; then
  printf '# No cluster branding key injected\n' > /etc/nginx/snippets/softswitch-branding-key.conf
  chmod 644 /etc/nginx/snippets/softswitch-branding-key.conf
fi
if [[ ! -f /etc/nginx/ssl/softswitch-portal.crt ]]; then
  openssl req -x509 -nodes -days 3650 -newkey rsa:2048 \
    -keyout /etc/nginx/ssl/softswitch-portal.key \
    -out /etc/nginx/ssl/softswitch-portal.crt \
    -subj "/CN=${NODE_HOSTNAME:-portal-web}/O=Ring2All" 2>/dev/null || true
fi

UPSTREAM_SERVERS=""
IFS=',' read -ra _ADMIN_ARR <<< "$PBX_ADMIN_IPS"
for aip in "${_ADMIN_ARR[@]}"; do
  aip="$(echo "$aip" | xargs)"
  [[ -z "$aip" ]] && continue
  UPSTREAM_SERVERS+="    server ${aip}:3001 max_fails=2 fail_timeout=15s;"$'\n'
done

cat << EOF > /etc/nginx/sites-available/softswitch-portal
upstream pbx_api_pool {
    ip_hash;
${UPSTREAM_SERVERS}}

server {
    listen 80 default_server;
    server_name _;
    return 301 https://\$host\$request_uri;
}

server {
    listen 443 ssl http2 default_server;
    server_name _;

    ssl_certificate     /etc/nginx/ssl/softswitch-portal.crt;
    ssl_certificate_key /etc/nginx/ssl/softswitch-portal.key;

    add_header X-Robots-Tag "none" always;
    access_log /var/log/nginx/portal_access.log;
    error_log  /var/log/nginx/portal_error.log;

    # Public branding endpoint with cluster-synchronized x-branding-key header
    location = /api/branding/by-domain {
        proxy_pass http://pbx_api_pool;
        proxy_http_version 1.1;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        include /etc/nginx/snippets/softswitch-branding-key.conf;
        proxy_next_upstream error timeout invalid_header http_502 http_503 http_504;
    }

    # Load-balanced API proxy across all PBX Control Plane servers
    location /api/ {
        proxy_pass http://pbx_api_pool;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        proxy_next_upstream error timeout invalid_header http_502 http_503 http_504;
        proxy_read_timeout 300s;
        client_max_body_size 100M;
    }

    # Realtime WebSocket signaling proxy
    location /ws/ {
        proxy_pass http://pbx_api_pool;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        proxy_read_timeout 86400;
        proxy_send_timeout 86400;
    }

    # Proxy shared branding & media uploads from PBX Admin pool
    location ^~ /uploads/ {
        proxy_pass https://${PRIMARY_ADMIN_IP}/uploads/;
        proxy_ssl_verify off;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
    }

    # Ring2All Connect (canonical /connect/ base path)
    location /connect/ {
        alias /var/www/softswitch/connect/;
        index index.html;
        try_files \$uri \$uri/ @connect_index;
    }
    location @connect_index {
        root /var/www/softswitch/connect;
        try_files /index.html =404;
    }
    location = /connect { return 301 /connect/; }
    location /portal/   { return 301 /connect/; }
    location = /portal  { return 301 /connect/; }
    location = /        { return 302 /connect/; }

    location / {
        root /var/www/softswitch/portal;
        index index.html;
        try_files \$uri \$uri/ /index.html;
    }
}
EOF

ln -sf /etc/nginx/sites-available/softswitch-portal /etc/nginx/sites-enabled/softswitch-portal
rm -f /etc/nginx/sites-enabled/default /etc/nginx/conf.d/default.conf 2>/dev/null || true
nginx -t
systemctl enable --now nginx
systemctl reload nginx

r2a_step 3 4 "Applying Edge DMZ firewall (nftables Profile C + NMS SNMPv3/Agent)"
NMS_SRC="${NMS_SERVER_IP:-$CLUSTER_SUBNET}"
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
        tcp dport { 80, 443 } 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
    }
    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 4 4 "Verifying Ring2All Connect HTTPS portal & upstream PBX API health"
r2a_wait_for_http_200 "https://127.0.0.1/connect/" 30 || r2a_fail "Connect portal /connect/ did not return HTTP 200."
r2a_wait_for_http_200 "https://127.0.0.1/api/health" 30 || r2a_fail "Proxied /api/health via pbx_api_pool did not return HTTP 200."

r2a_ok "Dedicated Ring2All Connect server deployed and load-balanced across PBX Admin pool."
r2a_result "{\"service\":\"pbx_portal_edge\",\"health\":\"ok\",\"upstreams\":\"${PBX_ADMIN_IPS}\"}"
