#!/bin/bash
# ============================================
# Ring2All PBX Platform - Automatic Installation
# Debian 13 (Trixie) · Class 5 Softswitch & FreeSWITCH
# ============================================
set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo ""
echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}  Ring2All PBX Platform Installer       ${NC}"
echo -e "${BLUE}  Class 5 Softswitch & Media Engine     ${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

# Check if running as root
if [ "$EUID" -ne 0 ]; then
    echo -e "${RED}Error: Please run as root${NC}"
    echo "Usage: sudo ./install-softswitch.sh"
    exit 1
fi

# Detect OS
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

# ==========================================
# STEP 1: Install Prerequisites
# ==========================================
echo ""
echo -e "${YELLOW}[1/7]${NC} Installing prerequisites..."
apt update
apt install -y curl gnupg2 sudo wget openvpn fail2ban nftables build-essential lsb-release python3

# ==========================================
# STEP 2: Add Ring2All Repository
# ==========================================
echo ""
echo -e "${YELLOW}[2/7]${NC} Adding Ring2All repositories..."

# Download and run repository setup script
cd /tmp
if [ -f setup_repo ]; then rm -f setup_repo; fi
wget -q https://repo.softswitchone.com/apt/setup_repo
chmod +x setup_repo
./setup_repo

# Ensure official nginx.org repository & pinning (fallback if remote setup_repo predates nginx.org)
if [ ! -f /etc/apt/sources.list.d/nginx.list ]; 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

# ==========================================
# STEP 3: Update Package Lists
# ==========================================
echo ""
echo -e "${YELLOW}[3/7]${NC} Updating package lists..."
apt update

# Ensure NGINX >= 1.30.7 from nginx.org is installed and compatible with sites-enabled / www-data before PBX packages
DEBIAN_FRONTEND=noninteractive apt-get 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 --now nginx 2>/dev/null || true

# ==========================================
# STEP 4: Install Node.js 22 LTS (Security Patch >= v22.23.4)
# ==========================================
echo ""
echo -e "${YELLOW}[4/7]${NC} Installing Node.js 22 LTS (Security Patch >= v22.23.4)..."
apt install -y nodejs
echo -e "${GREEN}✓${NC} Node.js $(node --version) installed"

# ==========================================
# STEP 5: Install PostgreSQL and ODBC
# ==========================================
echo ""
echo -e "${YELLOW}[5/7]${NC} Installing PostgreSQL 17 and ODBC drivers..."

if command -v psql &>/dev/null; then
    echo -e "${GREEN}✓${NC} PostgreSQL $(psql --version | awk '{print $3}') already installed"
else
    echo -e "${BLUE}Adding PostgreSQL official repository...${NC}"
    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 2>&1
    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 update -qq
fi

apt install -y postgresql-17 odbc-postgresql unixodbc

# Ensure PostgreSQL is running
systemctl enable postgresql
systemctl start postgresql

# ==========================================
# STEP 6: Install Softswitch PBX Database
# ==========================================
echo ""
echo -e "${YELLOW}[6/7]${NC} Installing Softswitch PBX Database..."
apt install -y softswitch-pbx-db

# ==========================================
# STEP 7: Install Softswitch PBX Suite
# ==========================================
echo ""
echo -e "${YELLOW}[7/7]${NC} Installing Softswitch PBX components..."

# Installing softswitch-pbx-all installs the complete PBX suite (API, Admin, Portal, Switchboard, FreeSWITCH, Audios)
apt install -y softswitch-pbx-all

# ==========================================
# POST-INSTALLATION: Verify Services
# ==========================================
echo ""
echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}  Verifying Installation${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

# Check PostgreSQL
if systemctl is-active --quiet postgresql; then
    echo -e "${GREEN}✓${NC} PostgreSQL is running"
else
    echo -e "${RED}✗${NC} PostgreSQL is NOT running"
fi

# Check FreeSWITCH
if systemctl is-active --quiet freeswitch; then
    echo -e "${GREEN}✓${NC} FreeSWITCH is running"
else
    echo -e "${YELLOW}!${NC} FreeSWITCH is NOT running - starting now..."
    systemctl start freeswitch
    sleep 2
    if systemctl is-active --quiet freeswitch; then
        echo -e "${GREEN}✓${NC} FreeSWITCH started successfully"
    else
        echo -e "${RED}✗${NC} FreeSWITCH failed to start"
        echo "   Check logs: journalctl -u freeswitch -n 50"
    fi
fi

# Check API
if systemctl is-active --quiet softswitch-api; then
    echo -e "${GREEN}✓${NC} Softswitch API is running"
else
    echo -e "${YELLOW}!${NC} Softswitch API is NOT running"
fi

# Check Nginx
if systemctl is-active --quiet nginx; then
    echo -e "${GREEN}✓${NC} Nginx is running"
else
    echo -e "${YELLOW}!${NC} Nginx is NOT running"
fi

# ==========================================
# SECURITY: Enable Security Services
# ==========================================
echo ""
echo -e "${BLUE}Enabling security services...${NC}"

# Enable and start fail2ban
systemctl enable fail2ban
systemctl start fail2ban
if systemctl is-active --quiet fail2ban; then
    echo -e "${GREEN}✓${NC} fail2ban is running"
    
    # Install r2a-fail2ban manager if not already installed
    if ! command -v r2a-fail2ban &> /dev/null; then
        for f2b_src in \
            "/usr/share/softswitch-pbx-telephony/scripts/fail2ban-manager.sh" \
            "/etc/freeswitch/nftables/scripts/fail2ban-manager.sh"; do
            if [ -f "$f2b_src" ]; then
                echo -e "${BLUE}  Installing fail2ban manager from ${f2b_src}...${NC}"
                cp "$f2b_src" /usr/local/bin/r2a-fail2ban
                chmod 755 /usr/local/bin/r2a-fail2ban
                break
            fi
        done
    fi

    # Apply SoftSwitch configuration (generates jail.local with FreeSWITCH SIP jail)
    if command -v r2a-fail2ban &> /dev/null; then
        echo -e "${BLUE}  Applying SoftSwitch fail2ban configuration...${NC}"
        r2a-fail2ban apply 2>/dev/null && echo -e "${GREEN}✓${NC} fail2ban SIP jail configured" || echo -e "${YELLOW}!${NC} fail2ban SIP jail - run 'r2a-fail2ban apply' after database is seeded"
    else
        echo -e "${YELLOW}!${NC} r2a-fail2ban not found - run 'r2a-fail2ban apply' after full setup"
    fi
else
    echo -e "${YELLOW}!${NC} fail2ban is NOT running"
fi

# Enable and start nftables (firewall)
systemctl enable nftables
systemctl start nftables 2>/dev/null || true
if systemctl is-active --quiet nftables; then
    echo -e "${GREEN}✓${NC} nftables is running"
else
    echo -e "${YELLOW}!${NC} nftables is enabled but not running (may need reboot or configuration)"
fi

# Enable openvpn (only enable, do not start - requires configuration)
systemctl enable openvpn
echo -e "${GREEN}✓${NC} openvpn is enabled (configure /etc/openvpn/ before starting)"

# 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"
}
configure_ring2all_motd "PBX"

# Get server IP
SERVER_IP=$(hostname -I | awk '{print $1}')

echo ""
echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}  Installation Complete!${NC}"
echo -e "${GREEN}========================================${NC}"
echo ""
echo "Access the web applications at:"
echo -e "  Admin Dashboard:      ${BLUE}https://${SERVER_IP}/${NC}"
echo -e "  User Self-Service:    ${BLUE}https://${SERVER_IP}/portal/${NC}"
echo -e "  Operator Switchboard: ${BLUE}https://${SERVER_IP}/switchboard/${NC}"
echo ""
echo "Default credentials:"
echo "  User: admin"
echo "  Password: (set on first login)"
echo ""
echo "SIP Registration:"
echo "  Server: ${SERVER_IP}"
echo "  Domain: ${SERVER_IP}"
echo ""
echo "Useful commands:"
echo "  systemctl status freeswitch"
echo "  systemctl status softswitch-api"
echo "  fs_cli"
echo ""
