#!/bin/bash
# ==============================================================================
# Ring2All NCX Platform — Automatic Modular Installer
# Debian 13 (Trixie) / Debian 12 (Bookworm)
# Neural Customer Experience (CCaaS, Inbound ACD, Dialer, WFM, QM & Agent Assist)
# ==============================================================================
set -e

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

PROFILE="${1:-compact}"

echo ""
echo -e "${BLUE}================================================================${NC}"
echo -e "${BLUE}  Ring2All NCX Platform — Automatic Installer                   ${NC}"
echo -e "${BLUE}  Neural Customer Experience (CCaaS) & Dialer Engine            ${NC}"
echo -e "${BLUE}  Profile: ${PROFILE} (compact | distributed)                   ${NC}"
echo -e "${BLUE}================================================================${NC}"
echo ""

if [ "$EUID" -ne 0 ]; then
    echo -e "${RED}Error: Please run as root: sudo $0 [compact|distributed]${NC}"
    exit 1
fi

if [ -f /etc/debian_version ]; then
    DEBIAN_VERSION=$(cat /etc/debian_version | cut -d. -f1)
    echo -e "${GREEN}✓${NC} Detected Debian $DEBIAN_VERSION"
else
    echo -e "${RED}Error: This script requires Debian Linux${NC}"
    exit 1
fi

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

# Step 1: Base Prerequisites & Official NGINX Repository
echo -e "${YELLOW}[1/6]${NC} Installing system prerequisites and NGINX (nginx.org)..."
apt update -qq
DEBIAN_FRONTEND=noninteractive apt install -y curl gnupg2 sudo wget ca-certificates lsb-release build-essential python3 ffmpeg
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
apt update -qq
DEBIAN_FRONTEND=noninteractive apt install -y -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" nginx
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

# Step 2: Ensure Node.js 22 LTS
echo -e "${YELLOW}[2/6]${NC} Ensuring Node.js 22 LTS..."
if ! command -v node &>/dev/null || ! node --version | grep -q "^v22"; then
    mkdir -p /etc/apt/keyrings
    curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg 2>/dev/null || true
    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
    apt update -qq
    DEBIAN_FRONTEND=noninteractive apt install -y nodejs
fi
echo -e "${GREEN}✓${NC} Node.js $(node --version)"

# Step 3: Install Ring2All NCX Packages
echo -e "${YELLOW}[3/6]${NC} Installing Ring2All NCX packages..."
if [ -d "/usr/src/softswitch/deb" ]; then
    dpkg -i /usr/src/softswitch/deb/softswitch-ncx*.deb 2>/dev/null || apt-get install -f -y
else
    echo "Installing via APT repository..."
    apt install -y softswitch-ncx-api softswitch-ncx-web softswitch-ncx-db
    if [ "$PROFILE" = "compact" ]; then
        apt install -y softswitch-ncx-stt || echo "Optional STT package skipped"
    fi
fi

# Step 4: Configure Profile
echo -e "${YELLOW}[4/6]${NC} Applying configuration profile: ${PROFILE}..."
mkdir -p /etc/softswitch
if [ "$PROFILE" = "compact" ]; then
    echo "Configuring Compact single-node profile..."
    # Local STT URL and local DB
    sed -i 's|^NCX_STT_BASE_URL=.*|NCX_STT_BASE_URL=http://127.0.0.1:18090|' /etc/softswitch/ncx.env 2>/dev/null || true
else
    echo "Configuring Distributed profile..."
    echo "Please set NCX_STT_BASE_URL and TELEPHONY_DATABASE_URL in /etc/softswitch/ncx.env for your remote nodes."
fi

# Step 5: Service Management (Fail-Open Telephony Guarantee)
echo -e "${YELLOW}[5/6]${NC} Enabling and starting NCX services..."
systemctl daemon-reload
systemctl enable softswitch-ncx-api
systemctl start softswitch-ncx-api

if [ "$PROFILE" = "compact" ] && systemctl list-unit-files | grep -q softswitch-ncx-stt.service; then
    systemctl enable softswitch-ncx-stt
    systemctl start softswitch-ncx-stt || true
fi

# Step 6: Health Verification
echo -e "${YELLOW}[6/6]${NC} Verifying NCX API health..."
sleep 2
if curl -s http://127.0.0.1:3008/health | grep -q "Ring2All NCX"; then
    echo -e "${GREEN}✓ Ring2All NCX API is HEALTHY on port 3008${NC}"
else
    echo -e "${YELLOW}Warning: NCX API starting up or needs database configuration in /etc/softswitch/ncx.env${NC}"
fi

# Configure Ring2All SSH Login MOTD Banner (AUTO keeps PBX primary on co-located PBX+NCX hosts)
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"
}
configure_ring2all_motd "AUTO"

echo ""
echo -e "${GREEN}================================================================${NC}"
echo -e "${GREEN}  🎉 Ring2All NCX Platform Installation Complete!             ${NC}"
echo -e "${GREEN}  Profile   : ${PROFILE}                                        ${NC}"
echo -e "${GREEN}  API Status: systemctl status softswitch-ncx-api               ${NC}"
echo -e "${GREEN}  Console   : https://${SERVER_IP}/connect/ncx-console          ${NC}"
echo -e "${GREEN}================================================================${NC}"
