#!/bin/bash
# ============================================
# Softswitch Platform - Automatic Installation
# Single Server (All-in-One) Setup
# ============================================
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}  Softswitch Platform Installer${NC}"
echo -e "${BLUE}  Single Server (All-in-One)${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

# ==========================================
# 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 http://repo.ring2all.com/apt/setup_repo
chmod +x setup_repo
./setup_repo

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

# ==========================================
# STEP 4: Install Node.js 22 LTS
# ==========================================
echo ""
echo -e "${YELLOW}[4/7]${NC} Installing Node.js 22 LTS..."
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..."
apt install -y postgresql-17 odbc-postgresql unixodbc

# Ensure PostgreSQL is running
systemctl enable postgresql
systemctl start postgresql

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

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

# Admin panel and API
apt install -y softswitch-admin

# Telephony (FreeSWITCH configuration + Lua scripts)
apt install -y softswitch-telephony

# ==========================================
# 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"
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)"

# 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 admin panel at:"
echo -e "  ${BLUE}http://${SERVER_IP}${NC}"
echo ""
echo "Default credentials:"
echo "  Email: admin@main.local"
echo "  Password: (set on first login)"
echo ""
echo "SIP Registration:"
echo "  Server: ${SERVER_IP}"
echo "  Domain: main.local"
echo ""
echo "Useful commands:"
echo "  systemctl status freeswitch"
echo "  systemctl status softswitch-api"
echo "  fs_cli"
echo ""
