#!/bin/bash
# ==============================================================================
# Ring2All DMS Platform — Automatic Modular Installer
# Debian 13 (Trixie) · Device Management System & Auto-Provisioning Server
# ==============================================================================
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 DMS Platform — Automatic Installer                   ${NC}"
echo -e "${BLUE}  Device Management System & Provisioning Hub                   ${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 tftpd-hpa
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 Server
echo -e "${YELLOW}[4/6]${NC} Ensuring PostgreSQL server..."
if ! command -v psql &>/dev/null || ! systemctl is-active --quiet postgresql 2>/dev/null; then
    apt update -qq
    apt install -y postgresql postgresql-contrib
fi
systemctl enable --now postgresql

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

# Step 6: Verify Services & Nginx
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-dms-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 "DMS"

echo ""
echo -e "${GREEN}================================================================${NC}"
echo -e "${GREEN}  Ring2All DMS Platform Installed Successfully!                 ${NC}"
echo -e "${GREEN}================================================================${NC}"
echo ""
echo "Access DMS portal:"
echo -e "  DMS Web Console:  ${BLUE}http://${SERVER_IP}/${NC} or ${BLUE}https://${SERVER_IP}/${NC}"
echo -e "  DMS Provisioning: ${BLUE}http://${SERVER_IP}/cfg/{mac}${NC}"
echo ""
