#!/usr/bin/env bash
# ==============================================================================
# 31-pbx-admin.sh — Phase 3A: PBX Control Plane (pbx-admin-01)
# Mounts GlusterFS (ss-uploads + ss-recordings with GID 2000), installs PBX API/Admin,
# applies Manual 19 Trap #5 (SSLMode=disable, PGPORT=5000, DB_SSL_MODE=disable) & Profile A 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}"
INCLUDE_PORTALS="${INCLUDE_PORTALS:-true}"
PBX_ADMIN_IPS="${PBX_ADMIN_IPS:-${NODE_IP:-}}"
PBX_EDGE_IPS="${PBX_EDGE_IPS:-}"

r2a_step 1 6 "Verifying isolated PBX database credentials via local HAProxy :5000"
[[ -f /etc/softswitch/pbx-db-credentials ]] || r2a_fail "/etc/softswitch/pbx-db-credentials missing (must be staged by NMS)."
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_admin -tAc "SELECT 1" >/dev/null \
  || r2a_fail "Database connectivity check via 127.0.0.1:5000 failed."

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

r2a_step 3 6 "Installing Ring2All PBX Control Plane packages"
r2a_setup_ring2all_repo
apt-get install -y nodejs nginx certbot python3-certbot-nginx

PKGS=(softswitch-pbx-api softswitch-pbx-monitoring-api softswitch-pbx-admin)
if [[ "$INCLUDE_PORTALS" == "true" ]]; then
  PKGS+=(softswitch-pbx-portal softswitch-pbx-switchboard)
fi
apt-get install -y "${PKGS[@]}"

r2a_step 4 6 "Applying Patroni HAProxy SSLMode=disable, shared cluster secrets & media permissions (GID 2000)"
if [[ -f /etc/odbc.ini ]]; then
  sed -i 's/SSLMode = prefer/SSLMode = disable/g' /etc/odbc.ini
fi

# Build cluster-wide CORS allowlist covering all PBX Admin, Connect, and Switchboard servers
CORS_ORIGINS_VAL="https://${NODE_IP:-127.0.0.1},http://${NODE_IP:-127.0.0.1}"
for raw_list in "$PBX_ADMIN_IPS" "$PBX_EDGE_IPS"; do
  [[ -z "$raw_list" ]] && continue
  IFS=',' read -ra _IPS <<< "$raw_list"
  for ip in "${_IPS[@]}"; do
    ip="$(echo "$ip" | xargs)"
    [[ -z "$ip" ]] && continue
    if [[ ",${CORS_ORIGINS_VAL}," != *",https://${ip},"* ]]; then
      CORS_ORIGINS_VAL+=",https://${ip},http://${ip}"
    fi
  done
done

if [[ -f /etc/softswitch/api.env ]]; then
  r2a_set_env_kv /etc/softswitch/api.env "PGPORT" "5000"
  r2a_set_env_kv /etc/softswitch/api.env "DB_SSL_MODE" "disable"
  r2a_set_env_kv /etc/softswitch/api.env "DEPLOYMENT_MODE" "cluster"
  [[ -n "${PBX_JWT_SECRET:-}" ]] && r2a_set_env_kv /etc/softswitch/api.env "JWT_SECRET" "$PBX_JWT_SECRET"
  [[ -n "${PBX_JWT_REFRESH_SECRET:-}" ]] && r2a_set_env_kv /etc/softswitch/api.env "JWT_REFRESH_SECRET" "$PBX_JWT_REFRESH_SECRET"
  [[ -n "${PBX_ENCRYPTION_KEY:-}" ]] && r2a_set_env_kv /etc/softswitch/api.env "ENCRYPTION_KEY" "$PBX_ENCRYPTION_KEY"
  [[ -n "${PBX_OPENVPN_ENCRYPTION_KEY:-}" ]] && r2a_set_env_kv /etc/softswitch/api.env "OPENVPN_ENCRYPTION_KEY" "$PBX_OPENVPN_ENCRYPTION_KEY"
  [[ -n "${PBX_BACKUP_ENCRYPTION_KEY:-}" ]] && r2a_set_env_kv /etc/softswitch/api.env "BACKUP_ENCRYPTION_KEY" "$PBX_BACKUP_ENCRYPTION_KEY"
  [[ -n "${PBX_SQIDS_ALPHABET:-}" ]] && r2a_set_env_kv /etc/softswitch/api.env "SQIDS_ALPHABET" "$PBX_SQIDS_ALPHABET"
  [[ -n "${PBX_PUBLIC_BRANDING_API_KEY:-}" ]] && r2a_set_env_kv /etc/softswitch/api.env "PUBLIC_BRANDING_API_KEY" "$PBX_PUBLIC_BRANDING_API_KEY"
  [[ -n "${INTERNAL_SERVICE_TOKEN:-}" ]] && r2a_set_env_kv /etc/softswitch/api.env "INTERNAL_SERVICE_TOKEN" "$INTERNAL_SERVICE_TOKEN"
  chmod 600 /etc/softswitch/api.env
fi

# Keep Nginx branding proxy header snippet synchronized with active PUBLIC_BRANDING_API_KEY
# (otherwise /api/branding/by-domain returns 401 INVALID_API_KEY and UI falls back to generic title)
CUR_BRANDING_KEY="$(grep '^PUBLIC_BRANDING_API_KEY=' /etc/softswitch/api.env 2>/dev/null | head -n 1 | cut -d= -f2- | tr -d '\r')"
if [[ -n "${CUR_BRANDING_KEY:-}" ]]; then
  mkdir -p /etc/nginx/snippets
  printf 'proxy_set_header x-branding-key "%s";\n' "$CUR_BRANDING_KEY" > /etc/nginx/snippets/softswitch-branding-key.conf
  chmod 644 /etc/nginx/snippets/softswitch-branding-key.conf
fi

# Synchronize Monitoring API JWT/SSO/Encryption keys so Switchboard SSO works across all pbx-admin & edge nodes
if [[ -f /etc/softswitch/monitoring.env ]]; then
  r2a_set_env_kv /etc/softswitch/monitoring.env "DEPLOYMENT_MODE" "cluster"
  [[ -n "${PBX_JWT_SECRET:-}" ]] && r2a_set_env_kv /etc/softswitch/monitoring.env "JWT_SECRET" "$PBX_JWT_SECRET"
  [[ -n "${PBX_JWT_SECRET:-}" ]] && r2a_set_env_kv /etc/softswitch/monitoring.env "ADMIN_SSO_SECRET" "$PBX_JWT_SECRET"
  [[ -n "${PBX_ENCRYPTION_KEY:-}" ]] && r2a_set_env_kv /etc/softswitch/monitoring.env "ENCRYPTION_KEY" "$PBX_ENCRYPTION_KEY"
  r2a_set_env_kv /etc/softswitch/monitoring.env "CORS_ORIGINS" "$CORS_ORIGINS_VAL"
  chown root:softswitch /etc/softswitch/monitoring.env 2>/dev/null || true
  chmod 640 /etc/softswitch/monitoring.env 2>/dev/null || true
fi

if id -u softswitch >/dev/null 2>&1; then
  usermod -aG "${MEDIA_GROUP:-r2a-media}" softswitch || true
fi

# Symlink PBX Admin recording, MOH domain, and system music paths to shared cluster storage
# so MOH uploads (/usr/share/freeswitch/recordings/domains/<domain>/moh/<class>), IVR prompts,
# custom recordings, system music, and call recordings are shared atomically with every Telephony node.
mkdir -p /var/lib/softswitch/recordings/domains /usr/share/softswitch/sounds/music
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 /usr/share/freeswitch/sounds/music && ! -L /usr/share/freeswitch/sounds/music ]]; then
  cp -an /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}" /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

# Ensure NTP drop-in directory exists and grant softswitch-api RW access to cluster storage mounts & NTP
mkdir -p /etc/systemd/timesyncd.conf.d /etc/systemd/system/softswitch-api.service.d
chmod 755 /etc/systemd/timesyncd.conf.d
cat << 'EOF' > /etc/systemd/system/softswitch-api.service.d/10-cluster-storage.conf
[Service]
ReadWritePaths=-/var/lib/softswitch/recordings -/var/lib/freeswitch/recordings -/usr/share/freeswitch/recordings -/usr/share/softswitch/sounds/music -/usr/share/freeswitch/sounds/music -/etc/systemd/timesyncd.conf.d
EOF
systemctl daemon-reload

# Ensure unattended RFPP v1 pairing (X-Internal-Token) resolves NULL created_by
# in ss_admin.public.api_keys to the primary active admin user.
PGPASSWORD="$DB_PASSWORD" psql -h 127.0.0.1 -p 5000 -U "$DB_USER" -d ss_admin -v ON_ERROR_STOP=1 -q << 'EOSQL' || true
CREATE OR REPLACE FUNCTION public.trg_api_keys_default_created_by()
RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
  IF NEW.created_by IS NULL THEN
    SELECT id INTO NEW.created_by
    FROM public.users
    WHERE is_active = true
    ORDER BY is_primary_admin DESC, id ASC
    LIMIT 1;
  END IF;
  RETURN NEW;
END;
$$;
DROP TRIGGER IF EXISTS api_keys_default_created_by ON public.api_keys;
CREATE TRIGGER api_keys_default_created_by
  BEFORE INSERT ON public.api_keys
  FOR EACH ROW
  EXECUTE FUNCTION public.trg_api_keys_default_created_by();
EOSQL

r2a_step 5 6 "Applying Management Plane firewall (nftables Profile A + 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

        # Internal cluster API/Monitoring access
        ip saddr ${CLUSTER_SUBNET} tcp dport { 3001, 3500 } 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 6 6 "Restarting PBX Control Plane services and verifying /api/health"
systemctl restart softswitch-api softswitch-monitoring-api nginx
r2a_wait_for_http_200 "https://127.0.0.1/api/health" 60 || r2a_fail "PBX Control Plane /api/health did not return 200."

r2a_ok "PBX Control Plane deployed and healthy."
r2a_result "{\"service\":\"pbx_admin\",\"health\":\"ok\",\"include_portals\":${INCLUDE_PORTALS}}"
