#!/usr/bin/env bash
# ==============================================================================
# 51-bss-client.sh — Phase 5B: BSS Customer Portal with Hardened Nginx Perimeter
# Blocks ALL non-client /api/* administrative routes with HTTP 403 at Nginx layer.
# ==============================================================================
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

BSS_ADMIN_IPS="${BSS_ADMIN_IPS:-${BSS_ADMIN_IP:-}}"
[[ -n "$BSS_ADMIN_IPS" ]] || r2a_fail "BSS_ADMIN_IPS or BSS_ADMIN_IP is required."

r2a_step 1 4 "Installing Nginx, nftables, and softswitch-bss-client"
r2a_setup_ring2all_repo
apt-get install -y nginx nftables curl gnupg2 ca-certificates
apt-get install -y softswitch-bss-client

r2a_step 2 4 "Configuring Hardened Nginx Customer Perimeter (fail-closed 403 on back-office APIs)"
mkdir -p /etc/nginx/ssl /etc/nginx/sites-available /etc/nginx/sites-enabled
if [[ ! -f /etc/nginx/ssl/softswitch-bss-client.crt ]]; then
  openssl req -x509 -nodes -days 3650 -newkey rsa:2048 \
    -keyout /etc/nginx/ssl/softswitch-bss-client.key \
    -out /etc/nginx/ssl/softswitch-bss-client.crt \
    -subj "/CN=bss-client/O=Ring2All" 2>/dev/null || true
  chmod 600 /etc/nginx/ssl/softswitch-bss-client.key
  chmod 644 /etc/nginx/ssl/softswitch-bss-client.crt
fi

WEB_ROOT=""
for candidate in /var/www/softswitch/bss/client /var/www/softswitch-bss-client /var/www/ring2all-bss-client; do
  if [[ -f "${candidate}/index.html" ]]; then
    WEB_ROOT="$candidate"
    break
  fi
done
[[ -n "$WEB_ROOT" ]] || r2a_fail "BSS Customer Portal static bundle (index.html) not found after installing softswitch-bss-client."
chown -R www-data:www-data "$WEB_ROOT" 2>/dev/null || true

BSS_HTTPS_UPSTREAMS=""
IFS=',' read -ra _BSS_ARR <<< "$BSS_ADMIN_IPS"
for bip in "${_BSS_ARR[@]}"; do
  bip="$(echo "$bip" | xargs)"
  [[ -z "$bip" ]] && continue
  BSS_HTTPS_UPSTREAMS+="    server ${bip}:443 max_fails=2 fail_timeout=15s;"$'\n'
done

cat << EOF > /etc/nginx/sites-available/softswitch-bss-client
upstream bss_api_pool {
    ip_hash;
${BSS_HTTPS_UPSTREAMS}}

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

server {
    listen 443 ssl default_server;
    listen [::]:443 ssl default_server;
    http2 on;
    server_name _;
    add_header X-Robots-Tag "none" always;

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

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers off;

    root ${WEB_ROOT};
    index index.html;

    # Block ALL back-office administrative endpoints from being reached via customer perimeter
    location ~* ^/api/(?!(?:v1/)?(?:client(?:/|\$)|lnp/client(?:/|\$)|branding(?:/|\$)|languages(?:/|\$)|health(?:/|\$)|payments/webhooks/stripe(?:/|\$))).+ {
        default_type application/json;
        return 403 '{"error":"Forbidden: Administrative APIs are not accessible via customer perimeter"}';
    }

    error_page 429 = @rate_limited;
    location @rate_limited {
        default_type application/json;
        add_header Retry-After 5 always;
        add_header Cache-Control "no-store" always;
        return 429 '{"success":false,"error":"RATE_LIMIT_EXCEEDED","code":"RATE_LIMIT_EXCEEDED","retryAfter":5,"message":"Too many requests in a short period. Please wait a few seconds before trying again."}';
    }

    location /api/ {
        proxy_pass https://bss_api_pool;
        proxy_ssl_verify off;
        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 50M;
    }

    location ^~ /assets/branding/ {
        proxy_pass https://bss_api_pool/assets/branding/;
        proxy_ssl_verify off;
        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;
        proxy_next_upstream error timeout invalid_header http_502 http_503 http_504;
    }

    location ^~ /portal/ {
        alias ${WEB_ROOT}/;
        index index.html;
        try_files \$uri \$uri/ /portal/index.html;
    }

    location / {
        try_files \$uri \$uri/ /index.html;
    }
}
EOF

ln -sf /etc/nginx/sites-available/softswitch-bss-client /etc/nginx/sites-enabled/softswitch-bss-client
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 Customer Portal SPA (200), upstream API health (200), and fail-closed 403 perimeter"
SPA_CODE="$(curl -sk -o /dev/null -w '%{http_code}' https://127.0.0.1/ || echo '000')"
if [[ "$SPA_CODE" != "200" ]]; then
  r2a_fail "Customer Portal SPA check failed: expected HTTP 200 on /, got ${SPA_CODE} (web_root=${WEB_ROOT})."
fi
API_CODE="$(curl -sk -o /dev/null -w '%{http_code}' https://127.0.0.1/api/health || echo '000')"
if [[ "$API_CODE" != "200" ]]; then
  r2a_fail "Customer Portal upstream API check failed: expected HTTP 200 on /api/health, got ${API_CODE}."
fi
CODE="$(curl -sk -o /dev/null -w '%{http_code}' https://127.0.0.1/api/customers || echo '000')"
if [[ "$CODE" != "403" ]]; then
  r2a_fail "Customer perimeter check failed: expected HTTP 403 on /api/customers, got ${CODE}."
fi

r2a_ok "BSS Customer Portal deployed (${WEB_ROOT}) with HTTP 200 SPA, HTTP 200 API proxy, and HTTP 403 back-office perimeter isolation."
r2a_result "{\"service\":\"bss_client\",\"web_root\":\"${WEB_ROOT}\",\"spa_http_code\":200,\"api_health_http_code\":200,\"perimeter_check_http_code\":403}"
