#!/bin/bash
# ==============================================================================
#  setup-carrier-node.sh — Ring2All Carrier-Grade Cluster Node Provisioner
#  Target OS: Debian 13 (Trixie)
#
#  Roles supported:
#    --role=sbc-hub       : SBC Primary (Kamailio + RTPEngine + WireGuard Mesh Hub)
#    --role=sbc-backup    : SBC Standby (Kamailio + RTPEngine + WireGuard Peer)
#    --role=db-primary    : PostgreSQL 17 Master + Patroni + etcd
#    --role=db-standby    : PostgreSQL 17 Synchronous Standby + Patroni + etcd
#    --role=db-witness    : etcd Raft Quorum Witness (No DB engine needed)
#    --role=pbx           : FreeSWITCH 1.11+ Media Node (Ring2All PBX Core)
#    --role=web           : Ring2All PBX Web, BSS API/Web & Switchboard
#    --role=devices       : Ring2All DMS (Device Management System) API & Web
#
#  Usage example:
#    ./setup-carrier-node.sh --role=sbc-hub --node-ip=10.9.0.1 --hostname=sbc-01
#    ./setup-carrier-node.sh --role=pbx --node-ip=10.9.0.21 --hub-endpoint=198.51.100.10:51820 --hub-pubkey=ABC... --hostname=pbx-01
# ==============================================================================
set -e
set -o pipefail

# ── Styling & Colors ─────────────────────────────────────────────────────────
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
WHITE='\033[1;37m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
NC='\033[0m'

ok()    { echo -e "  ${GREEN}✔${NC} $*"; }
step()  { echo -e "  ${CYAN}──>${NC} $*"; }
warn()  { echo -e "  ${YELLOW}[!]${NC} $*"; }
fail()  { echo -e "  ${RED}[✗]${NC} $*"; exit 1; }
head_() { echo -e "\n${PURPLE}=== $* ===${NC}"; }

# ── Check Root Execution ──────────────────────────────────────────────────────
if [ "$EUID" -ne 0 ]; then
    fail "This script must be executed as root (sudo ./setup-carrier-node.sh)."
fi

# ── Detect OS ────────────────────────────────────────────────────────────────
if [ -f /etc/debian_version ]; then
    DEBIAN_VERSION=$(cut -d. -f1 < /etc/debian_version)
    if [ "$DEBIAN_VERSION" != "13" ] && [ "$DEBIAN_VERSION" != "trixie/sid" ]; then
        warn "Detected Debian $DEBIAN_VERSION. This cluster is optimized for Debian 13 (Trixie)."
    else
        ok "Detected Debian 13 (Trixie)."
    fi
else
    fail "Unsupported operating system. Debian 13 is strictly required."
fi

# ── Parameter Parsing ────────────────────────────────────────────────────────
ROLE=""
NODE_IP=""
HUB_ENDPOINT=""
HUB_PUBKEY=""
CUSTOM_HOSTNAME=""
SKIP_REPO=false

for arg in "$@"; do
    case $arg in
        --role=*)          ROLE="${arg#*=}" ;;
        --node-ip=*)       NODE_IP="${arg#*=}" ;;
        --hub-endpoint=*)  HUB_ENDPOINT="${arg#*=}" ;;
        --hub-pubkey=*)    HUB_PUBKEY="${arg#*=}" ;;
        --hostname=*)      CUSTOM_HOSTNAME="${arg#*=}" ;;
        --skip-repo)       SKIP_REPO=true ;;
        --help|-h)
            echo "Usage: ./setup-carrier-node.sh --role=[sbc-hub|sbc-backup|db-primary|db-standby|db-witness|pbx|web|devices|nms] [options]"
            echo ""
            echo "Options:"
            echo "  --role=<role>          Target cluster role (required)"
            echo "  --node-ip=<IP>         Private WireGuard mesh IP (e.g. 10.9.0.21)"
            echo "  --hub-endpoint=<host>  Public endpoint of SBC-01 WireGuard Hub (<IP>:51820)"
            echo "  --hub-pubkey=<key>     Base64 WireGuard public key of SBC-01 Hub"
            echo "  --hostname=<name>      Set system hostname"
            echo "  --skip-repo            Skip adding Ring2All apt repositories"
            exit 0
            ;;
        *)
            warn "Unknown parameter: $arg"
            ;;
    esac
done

if [ -z "$ROLE" ]; then
    fail "Missing required parameter: --role. Run with --help for details."
fi

head_ "Ring2All Carrier Node Provisioner: Initializing Role [$ROLE]"

# ── Set Hostname ──────────────────────────────────────────────────────────────
if [ -n "$CUSTOM_HOSTNAME" ]; then
    step "Configuring hostname: $CUSTOM_HOSTNAME"
    hostnamectl set-hostname "$CUSTOM_HOSTNAME"
    sed -i "s/127.0.1.1.*/127.0.1.1 $CUSTOM_HOSTNAME/" /etc/hosts 2>/dev/null || echo "127.0.1.1 $CUSTOM_HOSTNAME" >> /etc/hosts
    ok "Hostname set to $(hostname)"
fi

# ── Step 1: Base System Prerequisites ────────────────────────────────────────
head_ "Step 1: Installing Base Linux & Networking Packages"
apt-get update -y
DEBIAN_FRONTEND=noninteractive apt-get install -y \
    curl \
    gnupg2 \
    sudo \
    wget \
    wireguard \
    wireguard-tools \
    nftables \
    fail2ban \
    systemd-timesyncd \
    net-tools \
    jq \
    htop \
    rsync \
    ca-certificates \
    python3 \
    dnsutils

systemctl enable --now systemd-timesyncd
ok "System utilities and time synchronization enabled."

# ── Step 2: Ring2All Repositories ─────────────────────────────────────────────
if [ "$SKIP_REPO" = false ]; then
    head_ "Step 2: Configuring Ring2All Official Debian Repositories"
    mkdir -p /etc/apt/keyrings
    
    # Ring2All Repository Key
    if [ ! -f /etc/apt/keyrings/ring2all.gpg ]; then
        curl -fsSL https://repo.softswitchone.com/apt/gpgkey/ring2all.gpg | gpg --dearmor -o /etc/apt/keyrings/ring2all.gpg
        chmod 644 /etc/apt/keyrings/ring2all.gpg
    fi
    
    cat > /etc/apt/sources.list.d/ring2all.list << 'EOF'
deb [signed-by=/etc/apt/keyrings/ring2all.gpg] https://repo.softswitchone.com/apt/base stable main
deb [signed-by=/etc/apt/keyrings/ring2all.gpg] https://repo.softswitchone.com/apt/core stable main
deb [signed-by=/etc/apt/keyrings/ring2all.gpg] https://repo.softswitchone.com/apt/devel stable main
deb [signed-by=/etc/apt/keyrings/ring2all.gpg] https://repo.softswitchone.com/apt/extras stable main
deb [signed-by=/etc/apt/keyrings/ring2all.gpg] https://repo.softswitchone.com/apt/audios stable main
EOF
    
    # Node.js 22 LTS (For Web, API, BSS, Devices, NMS, SBC, Switchboard)
    if [ "$ROLE" = "web" ] || [ "$ROLE" = "devices" ] || [ "$ROLE" = "nms" ] || [ "$ROLE" = "monitoring" ] || [ "$ROLE" = "sbc-hub" ] || [ "$ROLE" = "sbc-backup" ] || [ "$ROLE" = "pbx" ]; then
        if [ ! -f /etc/apt/keyrings/nodesource.gpg ]; then
            curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg
            echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_22.x nodistro main" > /etc/apt/sources.list.d/nodesource.list
        fi
    fi

    # Official nginx.org repository (patched upstream Stable branch >= 1.30.7)
    if [ "$ROLE" = "web" ] || [ "$ROLE" = "devices" ] || [ "$ROLE" = "nms" ] || [ "$ROLE" = "monitoring" ] || [ "$ROLE" = "sbc-hub" ] || [ "$ROLE" = "sbc-backup" ]; then
        mkdir -p /usr/share/keyrings /etc/apt/sources.list.d /etc/apt/preferences.d
        NGINX_CODENAME=$(. /etc/os-release 2>/dev/null && echo "${VERSION_CODENAME:-}")
        [ -z "$NGINX_CODENAME" ] && NGINX_CODENAME=$(lsb_release -cs 2>/dev/null || echo "trixie")
        curl -fsSL https://nginx.org/keys/nginx_signing.key | gpg --dearmor --yes -o /usr/share/keyrings/nginx-archive-keyring.gpg 2>/dev/null || true
        chmod 644 /usr/share/keyrings/nginx-archive-keyring.gpg 2>/dev/null || true
        echo "deb [signed-by=/usr/share/keyrings/nginx-archive-keyring.gpg] https://nginx.org/packages/debian ${NGINX_CODENAME} nginx" > /etc/apt/sources.list.d/nginx.list
        printf "Package: *\nPin: origin nginx.org\nPin: release o=nginx\nPin-Priority: 900\n" > /etc/apt/preferences.d/99nginx
    fi

    apt-get update -y
    ok "Apt sources configured and updated."
fi

configure_nginx_compat() {
    if [ -f /etc/nginx/conf.d/default.conf ] && grep -qE "Welcome to nginx|/usr/share/nginx/html" /etc/nginx/conf.d/default.conf 2>/dev/null; then
        rm -f /etc/nginx/conf.d/default.conf
    fi
    mkdir -p /etc/nginx/conf.d /etc/nginx/sites-available /etc/nginx/sites-enabled /etc/nginx/ssl
    if [ -f /etc/nginx/nginx.conf ]; then
        sed -i -E 's|^[[:space:]]*user[[:space:]]+nginx;|user www-data;|' /etc/nginx/nginx.conf
        grep -q '/etc/nginx/sites-enabled/' /etc/nginx/nginx.conf || sed -i '/include \/etc\/nginx\/conf\.d\/\*\.conf;/a \    include /etc/nginx/sites-enabled/*;' /etc/nginx/nginx.conf
        grep -qE '^[[:space:]]*server_tokens\b' /etc/nginx/nginx.conf || sed -i '/http {/a \    server_tokens off;' /etc/nginx/nginx.conf
    fi
    systemctl enable nginx 2>/dev/null || true
    nginx -t 2>/dev/null && systemctl restart nginx 2>/dev/null || true
}

# ── Step 3: WireGuard Private Mesh Mesh Network ───────────────────────────────
head_ "Step 3: WireGuard Internal Mesh Layer (10.9.0.0/24)"

mkdir -p /etc/wireguard
chmod 700 /etc/wireguard

if [ "$ROLE" = "sbc-hub" ]; then
    # SBC-01 acts as the WireGuard Hub
    WG_KEY_FILE="/etc/wireguard/server_private.key"
    WG_PUB_FILE="/etc/wireguard/server_public.key"
    if [ ! -f "$WG_KEY_FILE" ]; then
        wg genkey | tee "$WG_KEY_FILE" | wg pubkey > "$WG_PUB_FILE"
        chmod 600 "$WG_KEY_FILE"
    fi
    SBC_PUBKEY=$(cat "$WG_PUB_FILE")
    SBC_PRIVKEY=$(cat "$WG_KEY_FILE")

    cat > /etc/wireguard/wg0.conf << EOF
[Interface]
Address = ${NODE_IP:-10.9.0.1}/24
ListenPort = 51820
PrivateKey = $SBC_PRIVKEY
SaveConfig = false

# Peer template: Add peers dynamically or via sbcConnectorService
EOF
    systemctl enable wg-quick@wg0
    systemctl restart wg-quick@wg0 || true
    
    ok "WireGuard Hub configured on ${NODE_IP:-10.9.0.1}:51820"
    echo -e "  ${YELLOW}SBC-01 Public Key:${NC} $SBC_PUBKEY"

else
    # Client node (PBX, DB, Web, Devices, SBC-Backup)
    if [ -n "$NODE_IP" ] && [ -n "$HUB_ENDPOINT" ] && [ -n "$HUB_PUBKEY" ]; then
        WG_KEY_FILE="/etc/wireguard/client_private.key"
        WG_PUB_FILE="/etc/wireguard/client_public.key"
        if [ ! -f "$WG_KEY_FILE" ]; then
            wg genkey | tee "$WG_KEY_FILE" | wg pubkey > "$WG_PUB_FILE"
            chmod 600 "$WG_KEY_FILE"
        fi
        CLIENT_PRIVKEY=$(cat "$WG_KEY_FILE")
        CLIENT_PUBKEY=$(cat "$WG_PUB_FILE")

        cat > /etc/wireguard/wg0.conf << EOF
[Interface]
Address = ${NODE_IP}/24
PrivateKey = $CLIENT_PRIVKEY

[Peer]
PublicKey = $HUB_PUBKEY
Endpoint = $HUB_ENDPOINT
AllowedIPs = 10.9.0.0/24
PersistentKeepalive = 25
EOF
        systemctl enable wg-quick@wg0
        systemctl restart wg-quick@wg0 || true
        ok "WireGuard client configured with IP $NODE_IP pointing to $HUB_ENDPOINT"
        echo -e "  ${YELLOW}Node Public Key (register on SBC-01):${NC} $CLIENT_PUBKEY"
    else
        warn "WireGuard parameters not fully provided (--node-ip, --hub-endpoint, --hub-pubkey). Skipping wg0 auto-connect."
    fi
fi

# ── Step 4: Role-Specific Deployment ──────────────────────────────────────────
head_ "Step 4: Executing Role Installation for [$ROLE]"

case "$ROLE" in
    sbc-hub|sbc-backup)
        step "Installing official NGINX (nginx.org) before Ring2All SBC packages..."
        DEBIAN_FRONTEND=noninteractive apt-get install -y -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" nginx certbot python3-certbot-nginx || true
        configure_nginx_compat
        step "Installing Ring2All SBC suite (softswitch-sbc)..."
        apt-get install -y softswitch-sbc-all || apt-get install -y softswitch-sbc-telephony softswitch-sbc-api softswitch-sbc-admin || true
        configure_nginx_compat
        
        # Configure firewall: Public SIP (5060), TLS (5061), RTP (20000-40000), WireGuard (51820), SSH (22)
        step "Applying SBC perimeter nftables rules..."
        cat > /etc/nftables.conf << 'EOF'
#!/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

        # Public WireGuard Hub
        udp dport 51820 accept

        # Public SIP Signaling
        udp dport { 5060, 5061 } accept
        tcp dport { 5060, 5061 } accept

        # Public RTP Media Relay
        udp dport 20000-40000 accept

        # Admin & Management (Public Web / SSH)
        tcp dport { 22, 80, 443, 3000, 3002 } accept

        # Internal Mesh (WireGuard Interface)
        iif "wg0" accept
    }
    chain forward {
        type filter hook forward priority 0; policy accept;
    }
    chain output {
        type filter hook output priority 0; policy accept;
    }
}
EOF
        systemctl enable --now nftables
        nft -f /etc/nftables.conf
        ok "SBC Edge node and perimeter firewall active."
        ;;

    db-primary|db-standby)
        step "Installing PostgreSQL 17 and HA dependencies..."
        DEBIAN_FRONTEND=noninteractive apt-get install -y postgresql-17 postgresql-contrib-17 etcd-server patroni pgbouncer || true
        
        # Secure Firewall: Stealth mode (drop all public traffic, only allow SSH and wg0 internal)
        step "Applying Zero-Exposure Database nftables rules..."
        cat > /etc/nftables.conf << 'EOF'
#!/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

        # SSH Management
        tcp dport 22 accept

        # Only allow internal WireGuard traffic
        iif "wg0" 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
        ok "PostgreSQL 17 HA Node ready. Public ports firewalled into stealth mode."
        ;;

    db-witness)
        step "Installing etcd Raft Quorum Witness..."
        DEBIAN_FRONTEND=noninteractive apt-get install -y etcd-server || true
        
        # Stealth firewall
        cat > /etc/nftables.conf << 'EOF'
#!/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

        # SSH Management
        tcp dport 22 accept

        # Internal WireGuard traffic only
        iif "wg0" 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
        ok "DB Quorum Arbiter node ready."
        ;;

    pbx)
        step "Installing FreeSWITCH 1.11+ Telephony Media Node..."
        DEBIAN_FRONTEND=noninteractive apt-get install -y softswitch-pbx-telephony unixodbc odbc-postgresql sox libsndfile1 || true
        
        # Stealth Firewall: PBX media node ONLY responds to WireGuard private mesh
        step "Applying Stealth PBX nftables rules..."
        cat > /etc/nftables.conf << 'EOF'
#!/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

        # SSH Management
        tcp dport 22 accept

        # All VoIP & ESL traffic accepted ONLY through wg0
        iif "wg0" 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
        ok "PBX Telephony Node installed and bound to private mesh."
        ;;

    web)
        step "Installing official NGINX (nginx.org) before Ring2All Web/BSS packages..."
        DEBIAN_FRONTEND=noninteractive apt-get install -y -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" \
            nginx certbot python3-certbot-nginx || true
        configure_nginx_compat
        step "Installing Ring2All PBX Web, BSS Web/API & Switchboard..."
        DEBIAN_FRONTEND=noninteractive apt-get install -y \
            softswitch-pbx-api \
            softswitch-pbx-admin \
            softswitch-pbx-portal \
            softswitch-pbx-switchboard \
            softswitch-bss-api \
            softswitch-bss-web || true
        configure_nginx_compat
            
        cat > /etc/nftables.conf << 'EOF'
#!/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

        # Public HTTPS / HTTP / SSH
        tcp dport { 22, 80, 443 } accept

        # Internal WireGuard traffic
        iif "wg0" accept
    }
    chain forward {
        type filter hook forward priority 0; policy accept;
    }
    chain output {
        type filter hook output priority 0; policy accept;
    }
}
EOF
        systemctl enable --now nftables
        nft -f /etc/nftables.conf
        ok "Web & BSS Application cluster node ready."
        ;;

    devices)
        step "Installing official NGINX (nginx.org) before Ring2All DMS packages..."
        DEBIAN_FRONTEND=noninteractive apt-get install -y -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" \
            nginx certbot python3-certbot-nginx || true
        configure_nginx_compat
        step "Installing Ring2All DMS (Device Management System)..."
        DEBIAN_FRONTEND=noninteractive apt-get install -y softswitch-dms-all || true
        configure_nginx_compat
        
        cat > /etc/nftables.conf << 'EOF'
#!/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

        # Public HTTPS / HTTP / SSH
        tcp dport { 22, 80, 443 } accept

        # Internal WireGuard traffic
        iif "wg0" accept
    }
    chain forward {
        type filter hook forward priority 0; policy accept;
    }
    chain output {
        type filter hook output priority 0; policy accept;
    }
}
EOF
        systemctl enable --now nftables
        nft -f /etc/nftables.conf
        ok "Ring2All DMS node ready."
        ;;

    nms|monitoring)
        step "Installing official NGINX (nginx.org) before Ring2All NMS packages..."
        DEBIAN_FRONTEND=noninteractive apt-get install -y -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" \
            nginx certbot python3-certbot-nginx || true
        configure_nginx_compat
        step "Installing Ring2All NMS (Neural Monitoring System)..."
        DEBIAN_FRONTEND=noninteractive apt-get install -y softswitch-nms-all || true
        configure_nginx_compat
        
        cat > /etc/nftables.conf << 'EOF'
#!/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

        # Public HTTPS / HTTP / SSH / Ping
        tcp dport { 22, 80, 443 } accept
        ip protocol icmp accept

        # Internal WireGuard traffic
        iif "wg0" accept
    }
    chain forward {
        type filter hook forward priority 0; policy accept;
    }
    chain output {
        type filter hook output priority 0; policy accept;
    }
}
EOF
        systemctl enable --now nftables
        nft -f /etc/nftables.conf
        ok "Ring2All NMS node ready."
        ;;

    *)
        fail "Unrecognized role: $ROLE"
        ;;
esac

# Configure Ring2All SSH Login MOTD Banner
configure_ring2all_motd() {
    local motd_role="${1:-AUTO}"
    local script_dir=""
    script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" 2>/dev/null && pwd || true)"
    if [ -n "$script_dir" ] && [ -f "${script_dir}/install-ring2all-motd.sh" ]; then
        bash "${script_dir}/install-ring2all-motd.sh" "$motd_role" || true
        return 0
    fi
    local tmp_motd
    tmp_motd=$(mktemp /tmp/ring2all-motd.XXXXXX)
    if curl -fsSL "https://repo.softswitchone.com/apt/install-ring2all-motd.sh" -o "$tmp_motd" 2>/dev/null \
        || wget -qO "$tmp_motd" "https://repo.softswitchone.com/apt/install-ring2all-motd.sh" 2>/dev/null; then
        bash "$tmp_motd" "$motd_role" || true
    fi
    rm -f "$tmp_motd"
}

case "$ROLE" in
    sbc-hub|sbc-backup) configure_ring2all_motd "SBC" ;;
    devices)            configure_ring2all_motd "DMS" ;;
    nms|monitoring)     configure_ring2all_motd "NMS" ;;
    *)                  configure_ring2all_motd "HUB" ;;
esac

head_ "Deployment of [$ROLE] completed successfully!"
echo -e "Internal WireGuard IP: ${GREEN}${NODE_IP:-'Not configured'}${NC}"
echo -e "Node Hostname:         ${CYAN}$(hostname)${NC}"
echo -e "Firewall Status:       ${GREEN}Active (nftables stealth mode)${NC}"
echo ""
