#!/bin/bash
# ==============================================================================
# Ring2All BSS Platform — Automatic Modular Installer
# Debian 13 (Trixie) · Carrier Business Support System & OCS Billing
# ==============================================================================
set -e

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

echo ""
echo -e "${BLUE}================================================================${NC}"
echo -e "${BLUE}  Ring2All BSS Platform — Automatic Installer                   ${NC}"
echo -e "${BLUE}  Real-Time OCS Billing, Converged Rating & Customer Portal     ${NC}"
echo -e "${BLUE}================================================================${NC}"
echo ""

if [ "$EUID" -ne 0 ]; then
    echo -e "${RED}Error: Please run as root: sudo $0${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
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: Add Ring2All Repository
echo -e "${YELLOW}[2/6]${NC} Configuring Ring2All APT repository..."
REPO_URL="https://repo.softswitchone.com/apt"
if ! grep -r "softswitchone.com/apt" /etc/apt/sources.list.d/ &>/dev/null; then
    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

    cat > /etc/apt/sources.list.d/ring2all.list << EOF
deb [signed-by=/etc/apt/keyrings/ring2all.gpg] ${REPO_URL}/core stable main
EOF
fi

# Step 3: Node.js 22 LTS (Security Patch >= v22.23.4)
echo -e "${YELLOW}[3/6]${NC} Ensuring Node.js 22 LTS (Security Patch >= v22.23.4)..."
mkdir -p /etc/apt/keyrings
if [ ! -f /etc/apt/sources.list.d/nodesource.list ]; then
    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
fi
apt install -y nodejs
echo -e "${GREEN}✓${NC} Node.js $(node --version) ready"

# Step 4: PostgreSQL 17
echo -e "${YELLOW}[4/6]${NC} Ensuring PostgreSQL 17..."
if ! command -v psql &>/dev/null; then
    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
    apt install -y postgresql-17 postgresql-contrib-17
fi
systemctl enable --now postgresql

# Step 5: Install Ring2All BSS Suite
echo -e "${YELLOW}[5/6]${NC} Installing Ring2All BSS packages..."
apt update -qq
apt install -y softswitch-bss-all || apt install -y softswitch-bss-db softswitch-bss-api softswitch-bss-web softswitch-bss-client

# Step 6: Verify Services
echo -e "${YELLOW}[6/6]${NC} Verifying systemd services & Nginx..."
rm -f /etc/nginx/sites-enabled/default 2>/dev/null || true
systemctl enable --now softswitch-bss-api.service 2>/dev/null || true
systemctl restart nginx 2>/dev/null || true

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"
}
configure_ring2all_motd "BSS"

echo ""
echo -e "${GREEN}================================================================${NC}"
echo -e "${GREEN}  Ring2All BSS Platform Installed Successfully!                 ${NC}"
echo -e "${GREEN}================================================================${NC}"
echo ""
echo "Access BSS portals:"
echo -e "  Admin Back-Office UI:    ${BLUE}https://${SERVER_IP}:8443/${NC}"
echo -e "  Customer Self-Care Store: ${BLUE}https://${SERVER_IP}:4433/${NC}"
echo -e "  BSS REST API:            ${BLUE}http://${SERVER_IP}:3002/api/v1/health${NC}"
echo ""
