#!/bin/bash
# ===========================================================================
#  install-sbc.sh — Softswitch SBC Platform Modular & One-Touch Installer
#  Debian 13 (Trixie)
#
#  Usage:
#    wget -O- https://repo.softswitchone.com/apt/install-sbc.sh | bash
#    ./install-sbc.sh [flags]
#
#  Installation Modes & Flags:
#    --all               Install complete SBC suite on single server (default)
#    --db-only           Install only database schemas (softswitch-sbc-db)
#    --api-only          Install only Admin API (softswitch-sbc-api)
#    --admin-only        Install only Admin Web Portal (softswitch-sbc-admin)
#    --telephony-only    Install only SIP & RTPEngine engine (softswitch-sbc-telephony)
#    --sbc-edge          Install Telephony + API + Web for multi-master edge node
#
#  Fine-tuning Flags:
#    --skip-repo         Skip Ring2All repository setup
#    --skip-kamdb        Skip Kamailio native DB initialization
#    --help              Show this help
# ===========================================================================
set -e
set -o pipefail

# ── Flags ─────────────────────────────────────────────────────────────────────
MODE="all"
SKIP_REPO=false
SKIP_KAMDB=false

for arg in "$@"; do
    case $arg in
        --all)            MODE="all" ;;
        --db-only)        MODE="db" ;;
        --api-only)       MODE="api" ;;
        --admin-only|--web-only) MODE="admin" ;;
        --telephony-only) MODE="telephony" ;;
        --sbc-edge)       MODE="edge" ;;
        --skip-repo)      SKIP_REPO=true ;;
        --skip-kamdb)     SKIP_KAMDB=true ;;
        --help|-h)
            grep '^#' "$0" | head -25 | sed 's/^# \?//'
            exit 0 ;;
    esac
done

# ── 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'
NC='\033[0m'

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

# ── Banner ────────────────────────────────────────────────────────────────────
echo ""
echo -e "${BLUE}================================================================${NC}"
echo -e "${BLUE}  Softswitch SBC Platform — Modular Installer                  ${NC}"
echo -e "${BLUE}  Mode: ${MODE}                                                ${NC}"
echo -e "${BLUE}  Debian 13 (Trixie)                                            ${NC}"
echo -e "${BLUE}================================================================${NC}"
echo ""

if [ "$EUID" -ne 0 ]; then
    fail "Please run as root: sudo $0 $*"
    exit 1
fi

if [ -f /etc/debian_version ]; then
    ok "OS: $(grep PRETTY_NAME /etc/os-release | cut -d= -f2 | tr -d '"')"
else
    fail "This script requires Debian Linux"
    exit 1
fi

SERVER_IP=$(hostname -I 2>/dev/null | awk '{print $1}')
[ -z "$SERVER_IP" ] && SERVER_IP="127.0.0.1"
ok "Server IP: ${SERVER_IP}"

# ===========================================================================
# STEP 1 — Base System Prerequisites
# ===========================================================================
head_ "Step 1 — Installing system prerequisites"

apt-get update -qq
DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
    sudo curl wget gnupg2 apt-transport-https ca-certificates lsb-release \
    build-essential python3 openssl git rsync net-tools iproute2 dnsutils

ok "Base prerequisites installed"

# ===========================================================================
# STEP 2 — Repository Configuration
# ===========================================================================
head_ "Step 2 — Configuring Ring2All Repositories"

REPO_URL="https://repo.softswitchone.com/apt"

if [ "$SKIP_REPO" = true ]; then
    warn "--skip-repo: Skipping Ring2All repo setup"
elif grep -r "softswitchone.com/apt" /etc/apt/sources.list.d/ &>/dev/null; then
    ok "Ring2All repository already configured"
else
    step "Adding Ring2All GPG key..."
    mkdir -p /etc/apt/keyrings
    curl -fsSL "${REPO_URL}/gpgkey/ring2all.gpg" \
        | gpg --dearmor -o /etc/apt/keyrings/ring2all.gpg 2>/dev/null || true
    chmod 644 /etc/apt/keyrings/ring2all.gpg 2>/dev/null || true

    step "Adding Ring2All repository sources..."
    cat > /etc/apt/sources.list.d/ring2all.list << EOF
deb [signed-by=/etc/apt/keyrings/ring2all.gpg] ${REPO_URL}/base stable main
deb [signed-by=/etc/apt/keyrings/ring2all.gpg] ${REPO_URL}/core stable main
deb [signed-by=/etc/apt/keyrings/ring2all.gpg] ${REPO_URL}/extras stable main
deb [signed-by=/etc/apt/keyrings/ring2all.gpg] ${REPO_URL}/devel stable main
EOF
    ok "Ring2All repository added"
fi

apt-get update -qq
ok "Package lists updated"

# ===========================================================================
# STEP 3 — Component-Specific Installation
# ===========================================================================

# ── Function: Install PostgreSQL 17 ──
install_postgres() {
    head_ "Installing PostgreSQL 17 & Initializing SBC Databases"
    if command -v psql &>/dev/null; then
        ok "PostgreSQL $(psql --version | awk '{print $3}') already installed"
    else
        install -d /usr/share/postgresql-common/pgdg
        curl -fsSL https://www.postgresql.org/media/keys/ACCC4CF8.asc \
            | gpg --dearmor -o /usr/share/postgresql-common/pgdg/apt.postgresql.org.gpg >/dev/null
        echo "deb [signed-by=/usr/share/postgresql-common/pgdg/apt.postgresql.org.gpg] https://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" \
            > /etc/apt/sources.list.d/pgdg.list
        apt-get update -qq
        DEBIAN_FRONTEND=noninteractive apt-get install -y postgresql-17 postgresql-contrib-17 unixodbc odbc-postgresql >/dev/null
        ok "PostgreSQL 17 installed"
    fi
    # Tune PostgreSQL max_connections for Kamailio multi-process pooling (53+ children)
    if [ -f /etc/postgresql/17/main/postgresql.conf ]; then
        sed -i 's/^max_connections = .*/max_connections = 300/' /etc/postgresql/17/main/postgresql.conf 2>/dev/null || true
    fi
    systemctl restart postgresql 2>/dev/null || systemctl enable --now postgresql 2>/dev/null || true

    mkdir -p /etc/softswitch
    chmod 755 /etc/softswitch

    # 1. Resolve or create SBC database credentials
    if [ -f /etc/softswitch/sbc-db-credentials ]; then
        source /etc/softswitch/sbc-db-credentials
        step "Using existing credentials in /etc/softswitch/sbc-db-credentials"
        if [ -z "${KAMAILIO_PASSWORD}" ]; then
            KAMAILIO_PASSWORD=$(openssl rand -hex 16)
            KAMAILIORO_PASSWORD=$(openssl rand -hex 16)
            cat >> /etc/softswitch/sbc-db-credentials << EOF
KAMAILIO_USER=kamailio
KAMAILIO_PASSWORD=${KAMAILIO_PASSWORD}
KAMAILIORO_PASSWORD=${KAMAILIORO_PASSWORD}
EOF
            chmod 600 /etc/softswitch/sbc-db-credentials
        fi
    elif [ -f /etc/softswitch/sbc-credentials ]; then
        source /etc/softswitch/sbc-credentials
        step "Using existing credentials in /etc/softswitch/sbc-credentials"
    else
        step "Generating new SBC database credentials in /etc/softswitch/sbc-db-credentials..."
        SBC_DB_PASS=$(openssl rand -base64 32 | tr -dc 'a-zA-Z0-9' | head -c 24)
        KAMAILIO_PASSWORD=$(openssl rand -hex 16)
        KAMAILIORO_PASSWORD=$(openssl rand -hex 16)
        cat > /etc/softswitch/sbc-db-credentials << EOF
# Ring2All SBC Database Credentials
DB_USER=sbc_user
DB_PASSWORD=${SBC_DB_PASS}
DB_HOST=127.0.0.1
DB_PORT=5432
DB_NAME=sbc_admin
KAMAILIO_USER=kamailio
KAMAILIO_PASSWORD=${KAMAILIO_PASSWORD}
KAMAILIORO_PASSWORD=${KAMAILIORO_PASSWORD}
EOF
        chmod 600 /etc/softswitch/sbc-db-credentials
        source /etc/softswitch/sbc-db-credentials
    fi

    # Keep compatibility symlink
    if [ ! -f /etc/softswitch/sbc-credentials ]; then
        ln -sf /etc/softswitch/sbc-db-credentials /etc/softswitch/sbc-credentials 2>/dev/null || true
    fi

    SBC_USER="${DB_USER:-sbc_user}"
    SBC_PASS="${DB_PASSWORD:-}"

    step "Configuring PostgreSQL roles for SBC (${SBC_USER}, kamailio)..."
    local KAM_PASS="${KAMAILIO_PASSWORD:-$(openssl rand -hex 16)}"
    local KAMRO_PASS="${KAMAILIORO_PASSWORD:-$(openssl rand -hex 16)}"
    sudo -u postgres psql -qc "
        DO \$\$ BEGIN
            IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = '${SBC_USER}') THEN
                CREATE ROLE ${SBC_USER} WITH LOGIN PASSWORD '${SBC_PASS}' NOSUPERUSER NOCREATEDB NOCREATEROLE;
            ELSE
                ALTER ROLE ${SBC_USER} WITH PASSWORD '${SBC_PASS}' NOSUPERUSER NOCREATEDB NOCREATEROLE;
            END IF;
            IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'sbc_user') THEN
                CREATE ROLE sbc_user WITH LOGIN PASSWORD '${SBC_PASS}' NOSUPERUSER NOCREATEDB NOCREATEROLE;
            ELSE
                ALTER ROLE sbc_user WITH PASSWORD '${SBC_PASS}' NOSUPERUSER NOCREATEDB NOCREATEROLE;
            END IF;
            IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'kamailio') THEN
                CREATE ROLE kamailio WITH LOGIN PASSWORD '${KAM_PASS}' NOSUPERUSER NOCREATEDB NOCREATEROLE;
            ELSE
                ALTER ROLE kamailio WITH PASSWORD '${KAM_PASS}' NOSUPERUSER NOCREATEDB NOCREATEROLE;
            END IF;
            IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'kamailioro') THEN
                CREATE ROLE kamailioro WITH LOGIN PASSWORD '${KAMRO_PASS}' NOSUPERUSER NOCREATEDB NOCREATEROLE;
            END IF;
        END \$\$;
    "

    step "Creating and verifying sbc_admin and kamailio databases..."
    for db in sbc_admin kamailio; do
        if ! sudo -u postgres psql -tAqc "SELECT 1 FROM pg_database WHERE datname='${db}';" 2>/dev/null | grep -q 1; then
            step "Creating database ${db}..."
            sudo -u postgres createdb -O "${SBC_USER}" "$db"
        else
            ok "Database ${db} already exists"
        fi
        sudo -u postgres psql -qc "GRANT ALL PRIVILEGES ON DATABASE ${db} TO ${SBC_USER};" 2>/dev/null || true
        sudo -u postgres psql -qc "GRANT ALL PRIVILEGES ON DATABASE ${db} TO sbc_user;" 2>/dev/null || true
        sudo -u postgres psql -qc "GRANT ALL PRIVILEGES ON DATABASE ${db} TO kamailio;" 2>/dev/null || true
    done
    ok "PostgreSQL roles and databases (${SBC_USER} -> sbc_admin & kamailio) ready"
}

# ── Function: Install Node.js 22 ──
install_nodejs() {
    head_ "Installing Node.js 22 LTS (Security Patch >= v22.23.4)"
    curl -fsSL https://deb.nodesource.com/setup_22.x | bash - >/dev/null 2>&1
    apt-get install -y nodejs >/dev/null 2>&1
    ok "Node.js $(node --version) ready"
}

# ── Function: Install Kamailio 6.x & RTPEngine ──
install_kamailio_rtpengine() {
    head_ "Installing Kamailio 6.x & Sipwise RTPEngine"
    KAM_KEYRING=/usr/share/keyrings/kamailio.gpg
    curl -fsSL https://deb.kamailio.org/kamailiodebkey.gpg \
        | gpg --dearmor -o "$KAM_KEYRING" 2>/dev/null || true

    echo "deb [signed-by=${KAM_KEYRING}] http://deb.kamailio.org/kamailio60 trixie main" \
        > /etc/apt/sources.list.d/kamailio.list

    apt-get update -qq 2>/dev/null || true
    
    # Try standard kamailio packages from deb.kamailio.org / Debian, fallback to sbc-kamailio
    DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
        kamailio kamailio-postgres-modules kamailio-tls-modules \
        kamailio-websocket-modules kamailio-utils-modules \
        kamailio-json-modules kamailio-extra-modules \
        kamailio-presence-modules kamcli \
        ngcp-rtpengine-daemon ngcp-rtpengine-utils \
        wireguard wireguard-tools nftables fail2ban \
        unixodbc unixodbc-dev odbc-postgresql lua5.4 lua-cjson 2>/dev/null || \
    DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
        sbc-kamailio sbc-kamailio-postgres-modules sbc-kamailio-tls-modules \
        sbc-kamailio-websocket-modules sbc-kamailio-utils-modules \
        sbc-kamailio-json-modules sbc-kamailio-extra-modules \
        sbc-kamailio-presence-modules kamcli \
        ngcp-rtpengine-daemon ngcp-rtpengine-utils \
        wireguard wireguard-tools nftables fail2ban \
        unixodbc unixodbc-dev odbc-postgresql lua5.4 lua-cjson 2>/dev/null || true

    mkdir -p /etc/kamailio
    if [ ! -s "/etc/kamailio/sbc-smr.cfg" ]; then
        cat << 'EOF' > /etc/kamailio/sbc-smr.cfg
# Smart Media Routing (SMR) Stubs
route[SMR_INBOUND] {
    return;
}

route[SMR_OUTBOUND] {
    return;
}
EOF
    fi

    if [ ! -s "/etc/kamailio/sbc-rtpengines.cfg" ]; then
        cat << 'EOF' > /etc/kamailio/sbc-rtpengines.cfg
# RTPEngine Socket Definition
modparam("rtpengine", "rtpengine_sock", "udp:127.0.0.1:2223")
EOF
    fi

    ok "Kamailio 6.x & RTPEngine ready"
}

# ── Function: Install Nginx ──
install_nginx() {
    head_ "Installing Nginx Web Server (nginx.org Stable)"
    mkdir -p /usr/share/keyrings /etc/apt/sources.list.d /etc/apt/preferences.d
    local codename
    codename=$(. /etc/os-release 2>/dev/null && echo "${VERSION_CODENAME:-}")
    [ -z "$codename" ] && 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 ${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
    apt-get update -qq
    DEBIAN_FRONTEND=noninteractive apt-get install -y -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" nginx certbot python3-certbot-nginx 2>/dev/null || true
    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 || systemctl enable --now nginx 2>/dev/null || true
    ok "Nginx $(nginx -v 2>&1 | awk -F/ '{print $2}') ready"
}

# ── Execution based on Mode ──
case "$MODE" in
    all)
        install_postgres
        install_nodejs
        install_nginx
        install_kamailio_rtpengine
        head_ "Installing Ring2All SBC Database schemas first"
        apt-get install -y softswitch-sbc-db
        head_ "Installing softswitch-sbc-all suite"
        apt-get install -y softswitch-sbc-all || apt-get install -y softswitch-sbc-telephony softswitch-sbc-api softswitch-sbc-admin

        # Restart and enable all core SBC services
        head_ "Restarting & Verifying SBC Services"
        systemctl daemon-reload 2>/dev/null || true
        systemctl restart ngcp-rtpengine-daemon 2>/dev/null || true
        systemctl restart sbc-api 2>/dev/null || true
        systemctl restart kamailio 2>/dev/null || true
        systemctl restart nginx 2>/dev/null || true
        ;;
    db)
        install_postgres
        head_ "Installing softswitch-sbc-db"
        apt-get install -y softswitch-sbc-db
        ;;
    api)
        install_nodejs
        head_ "Installing softswitch-sbc-api"
        apt-get install -y softswitch-sbc-api
        ;;
    admin)
        install_nginx
        head_ "Installing softswitch-sbc-admin"
        apt-get install -y softswitch-sbc-admin
        ;;
    telephony)
        install_kamailio_rtpengine
        head_ "Installing softswitch-sbc-telephony"
        apt-get install -y softswitch-sbc-telephony
        ;;
    edge)
        install_nodejs
        install_nginx
        install_kamailio_rtpengine
        head_ "Installing Edge SBC Stack (Telephony + API + Admin)"
        apt-get install -y softswitch-sbc-telephony softswitch-sbc-api softswitch-sbc-admin
        ;;
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 "${REPO_URL}/install-ring2all-motd.sh" -o "$tmp_motd" 2>/dev/null \
        || wget -qO "$tmp_motd" "${REPO_URL}/install-ring2all-motd.sh" 2>/dev/null; then
        bash "$tmp_motd" "$motd_role" || true
    fi
    rm -f "$tmp_motd"
}

case "$MODE" in
    all|edge) configure_ring2all_motd "SBC" ;;
    *)        configure_ring2all_motd "HUB" ;;
esac

echo ""
echo -e "${GREEN}================================================================${NC}"
echo -e "${GREEN}  Softswitch SBC Installation Completed (${MODE} mode)!          ${NC}"
echo -e "${GREEN}================================================================${NC}"
echo ""
