#!/bin/bash
# ─────────────────────────────────────────────────────────────────────────────
#  TheServerLicense — License Provisioning System
#  Copyright (c) Rapinova Group. All rights reserved.
#
#  Usage:  bash pre.sh <Product>
#          bash pre.sh --status
#          bash pre.sh --diagnose
# ─────────────────────────────────────────────────────────────────────────────

VERSION="1.0.0"
BUILD="2026.02.20"
# Customer-facing brand name. Must never show another brand's name.
BRAND_NAME="TheServerLicense"
MIRROR="https://mirror.resellercenter.ir"
# One neutral name on every brand (no brand in it). An old /var/log/tsl-installer.log is left alone.
LOG="/var/log/licence-installer.log"
RCBIN="/usr/local/RCBIN"
RCUPDATE="/usr/bin/RCUpdate"

# ── Theme ────────────────────────────────────────────────────────────────────
R='\033[0;31m'      # Red
G='\033[0;32m'      # Green
Y='\033[1;33m'      # Yellow
B='\033[0;34m'      # Blue
C='\033[0;36m'      # Cyan
W='\033[1;37m'      # White bold
D='\033[0;90m'      # Dim/gray
N='\033[0m'         # Reset
BLD='\033[1m'       # Bold
UL='\033[4m'        # Underline

# ── Product Registry ─────────────────────────────────────────────────────────
declare -A PRODUCT_CMD=(
    [cPanel]="tslzCP"
    [Plesk]="tslzPlesk"
    [LiteSpeed]="tslzLSWS"
    [CloudLinux]="tslzCLN"
    [Imunify360]="tslzImunify360"
    [CXS]="tslzCXS"
    [JetBackup]="tslzJetBackup"
    [Softaculous]="tslzSoftaculous"
    [Sitepad]="tslzSitepad"
    [WHMReseller]="tslzWHMReseller"
    [Virtualizor]="tslzVirtualizor"
    [OSM]="tslzOSM"
)

RHEL_ONLY="cPanel CloudLinux"
PRODUCTS_LIST="cPanel Plesk LiteSpeed CloudLinux Imunify360 CXS JetBackup Softaculous Sitepad WHMReseller Virtualizor OSM"

# ── Display Helpers ──────────────────────────────────────────────────────────

banner() {
    echo ""
    echo -e "${W}  ┌──────────────────────────────────────────────────┐${N}"
    echo -e "${W}  │                                                  │${N}"
    # Width-aware so any brand name keeps the box aligned.
    _bn_pad=$(( 25 - ${#BRAND_NAME} ))
    [ "$_bn_pad" -lt 1 ] && _bn_pad=1
    echo -e "${W}  │   ${C}${BRAND_NAME}${W}  License Provisioning$(printf '%*s' "$_bn_pad" '')│${N}"
    echo -e "${W}  │   ${D}v${VERSION} (${BUILD})${W}                               │${N}"
    echo -e "${W}  │                                                  │${N}"
    echo -e "${W}  └──────────────────────────────────────────────────┘${N}"
    echo ""
}

section() {
    echo ""
    echo -e "  ${W}$1${N}"
    echo -e "  ${D}$(printf '%.0s─' $(seq 1 ${#1}))${N}"
}

ok()   { echo -e "  ${G}✓${N}  $*"; }
fail() { echo -e "  ${R}✗${N}  $*"; }
warn() { echo -e "  ${Y}!${N}  $*"; }
info() { echo -e "  ${D}›${N}  $*"; }
step() { echo -e "  ${C}◆${N}  $*"; }

progress() {
    local msg="$1"
    echo -ne "  ${D}⟳${N}  ${msg}..."
}

progress_done() {
    echo -e "\r  ${G}✓${N}  $*"
}

progress_fail() {
    echo -e "\r  ${R}✗${N}  $*"
}

divider() {
    echo -e "  ${D}──────────────────────────────────────────────────${N}"
}

# ── Logging ──────────────────────────────────────────────────────────────────
log() {
    mkdir -p "$(dirname "$LOG")" 2>/dev/null
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" >> "$LOG" 2>/dev/null
}

# ── Step 1: Preflight ────────────────────────────────────────────────────────

preflight() {
    section "Preflight Checks"

    # Root
    if [ "$(id -u)" -ne 0 ]; then
        fail "Root access required"
        info "Run with: ${W}sudo bash pre.sh $PRODUCT${N}"
        exit 1
    fi
    ok "Root access confirmed"

    # Architecture (uname -m is reliable on ALL Linux, unlike uname -i)
    ARCH=$(uname -m)
    case "$ARCH" in
        x86_64|amd64)
            ok "Architecture: ${W}$ARCH${N} (64-bit)"
            ;;
        i*86|i686)
            fail "32-bit systems are not supported"
            exit 1
            ;;
        aarch64|arm64)
            warn "ARM64 detected — limited compatibility"
            ;;
        *)
            warn "Architecture: $ARCH (unverified)"
            ;;
    esac

    # OS Detection — uses /etc/os-release (works on ALL modern Linux)
    OS_FAMILY="" OS_NAME="" OS_VER="" PKG="" LIBDIR=""

    if [ -f /etc/os-release ]; then
        . /etc/os-release
        OS_NAME="$ID"
        OS_VER="$VERSION_ID"

        case "$OS_NAME" in
            almalinux|centos|rocky|rockylinux|cloudlinux|rhel|redhat|ol)
                OS_FAMILY="rhel"; PKG="yum"; LIBDIR="/usr/lib64" ;;
            fedora)
                OS_FAMILY="rhel"; PKG="dnf"; LIBDIR="/usr/lib64" ;;
            ubuntu)
                OS_FAMILY="debian"; PKG="apt-get"; LIBDIR="/lib/x86_64-linux-gnu" ;;
            debian)
                OS_FAMILY="debian"; PKG="apt-get"; LIBDIR="/lib/x86_64-linux-gnu" ;;
            *)
                if [ -f /etc/redhat-release ]; then
                    OS_FAMILY="rhel"; PKG="yum"; LIBDIR="/usr/lib64"; OS_NAME="rhel-compat"
                else
                    OS_FAMILY="unknown"
                fi
                ;;
        esac
    elif [ -f /etc/redhat-release ]; then
        OS_FAMILY="rhel"; PKG="yum"; LIBDIR="/usr/lib64"; OS_NAME="legacy-rhel"
        OS_VER=$(grep -oP '[0-9]+\.[0-9]+' /etc/redhat-release | head -1)
    fi

    if [ "$OS_FAMILY" = "unknown" ] || [ -z "$OS_FAMILY" ]; then
        fail "Unsupported operating system"
        info "Supported: AlmaLinux, CentOS, Rocky, CloudLinux, Ubuntu, Debian"
        exit 1
    fi

    local os_display="${OS_NAME^} ${OS_VER}"
    case "$OS_FAMILY" in
        rhel)   ok "Operating System: ${W}${os_display}${N} ${D}(RHEL family — fully supported)${N}" ;;
        debian) warn "Operating System: ${W}${os_display}${N} ${Y}(limited support — experimental)${N}" ;;
    esac

    ok "Package Manager: ${W}${PKG}${N}"

    log "OS=$OS_NAME $OS_VER FAMILY=$OS_FAMILY ARCH=$ARCH PKG=$PKG"
}

# ── Step 2: Product Validation ───────────────────────────────────────────────

# cPanel licensing needs the kernel's ipset support. RHEL 10 family kernels
# (AlmaLinux 10 etc.) ship without it, so cPanel would stay unlicensed
# however often this runs. Checked as a capability, not an OS version.
kernel_has_ipset() {
    modinfo ip_set >/dev/null 2>&1 || [ -d /sys/module/ip_set ]
}

validate_product() {
    local product="$1"
    [ -z "$product" ] && return 0

    section "Product Validation"

    # Check if product exists
    local valid=0
    for p in $PRODUCTS_LIST; do
        [ "$p" = "$product" ] && valid=1 && break
    done

    if [ "$valid" -eq 0 ]; then
        fail "Unknown product: ${W}${product}${N}"
        echo ""
        info "Available products:"
        for p in $PRODUCTS_LIST; do
            info "  ${W}$p${N}"
        done
        exit 1
    fi

    ok "Product: ${W}${product}${N}"

    # RHEL-only check
    if [ "$OS_FAMILY" != "rhel" ]; then
        for rp in $RHEL_ONLY; do
            if [ "$product" = "$rp" ]; then
                echo ""
                fail "${W}${product}${N} requires a RHEL-based operating system"
                echo ""
                info "Your system: ${W}${OS_NAME^} ${OS_VER}${N} (${OS_FAMILY} family)"
                info "${product} only runs on: AlmaLinux, CentOS, Rocky Linux, CloudLinux"
                echo ""
                info "This is a ${W}product limitation${N}, not a licensing issue."
                info "Please contact support and we'll help you move the licence to a supported system."
                exit 2
            fi
        done
        warn "Running ${W}${product}${N} on ${W}${OS_NAME^}${N} is experimental"
        info "The product supports this OS, but our provisioning has limited testing"
    else
        if [ "$product" = "cPanel" ] && ! kernel_has_ipset; then
            echo ""
            fail "${W}cPanel${N} cannot be licensed on ${W}${OS_NAME^} ${OS_VER}${N}"
            echo ""
            info "The cPanel licence needs ipset support in the kernel, and this kernel has none."
            info "Reinstall the server with ${W}AlmaLinux 9${N} or ${W}CloudLinux 9${N}, then run this again."
            info "Nothing is wrong with your licence: only the operating system needs to change."
            exit 2
        fi
        ok "OS compatibility: ${G}confirmed${N}"
    fi
}

# ── Step 3: System Preparation ───────────────────────────────────────────────

prepare_system() {
    section "System Preparation"

    # 3a. Dependencies
    local missing=""
    for tool in wget curl openssl unzip; do
        command -v "$tool" >/dev/null 2>&1 || missing="$missing $tool"
    done

    if [ -n "$missing" ]; then
        progress "Installing dependencies:${W}${missing}${N}"
        [ "$OS_FAMILY" = "debian" ] && $PKG update -y >> "$LOG" 2>&1
        $PKG install -y $missing >> "$LOG" 2>&1
        if [ $? -eq 0 ]; then
            progress_done "Dependencies installed:${W}${missing}${N}"
        else
            progress_fail "Some dependencies failed to install"
        fi
    else
        ok "Dependencies: ${D}wget, curl, openssl, unzip${N}"
    fi

    # 3b. Development libraries
    if [ "$OS_FAMILY" = "rhel" ]; then
        $PKG install -y libcurl-devel re2c >> "$LOG" 2>&1
        # Disable MySQL community repo if present
        [ -f /etc/yum.repos.d/mysql-community.repo ] && \
            sed -i "s|enabled=1|enabled=0|g" /etc/yum.repos.d/mysql-community.repo 2>/dev/null
    elif [ "$OS_FAMILY" = "debian" ]; then
        $PKG install -y libcurl4-openssl-dev re2c >> "$LOG" 2>&1
    fi
    ok "Development libraries: ${D}libcurl, re2c${N}"

    # 3c. Compatibility libraries (libssl.so.10 / libcrypto.so.10)
    local libs_installed=0
    if [ ! -f "$LIBDIR/libssl.so.10" ]; then
        wget -q -O /tmp/.libssl.so.10 "$MIRROR/libssl.so.10" 2>/dev/null
        if [ -f /tmp/.libssl.so.10 ]; then
            local md5=$(md5sum /tmp/.libssl.so.10 | awk '{print $1}')
            if [ "$md5" = "302a3c982a5ce32a6b5c229102ea891f" ]; then
                mkdir -p "$LIBDIR"
                cp /tmp/.libssl.so.10 "$LIBDIR/libssl.so.10"
                libs_installed=1
            fi
            rm -f /tmp/.libssl.so.10
        fi
    fi

    if [ ! -f "$LIBDIR/libcrypto.so.10" ]; then
        wget -q -O /tmp/.libcrypto.so.10 "$MIRROR/libcrypto.so.10" 2>/dev/null
        if [ -f /tmp/.libcrypto.so.10 ]; then
            local md5=$(md5sum /tmp/.libcrypto.so.10 | awk '{print $1}')
            if [ "$md5" = "cc736871585f4b1f64f0ce584a00be1c" ]; then
                mkdir -p "$LIBDIR"
                cp /tmp/.libcrypto.so.10 "$LIBDIR/libcrypto.so.10"
                libs_installed=1
            fi
            rm -f /tmp/.libcrypto.so.10
        fi
    fi

    [ "$libs_installed" -eq 1 ] && ok "Compatibility libraries installed to ${D}${LIBDIR}${N}" || \
        ok "Compatibility libraries: ${D}already present${N}"

    # 3d. Debian-specific fixes
    if [ "$OS_FAMILY" = "debian" ]; then
        echo ""
        info "${D}Applying platform compatibility patches...${N}"

        # Fix: RCUpdate is 32-bit ELF — needs i386 support
        if ! dpkg --print-foreign-architectures 2>/dev/null | grep -q i386; then
            progress "Enabling 32-bit runtime"
            dpkg --add-architecture i386 >> "$LOG" 2>&1
            $PKG update -y >> "$LOG" 2>&1
            $PKG install -y libc6:i386 >> "$LOG" 2>&1
            [ $? -eq 0 ] && progress_done "32-bit runtime enabled" || progress_fail "32-bit runtime failed"
        else
            ok "32-bit runtime: ${D}already enabled${N}"
        fi

        # Fix: RCBIN/bin/php needs /lib64/ld-linux-x86-64.so.2
        if [ ! -f /lib64/ld-linux-x86-64.so.2 ]; then
            mkdir -p /lib64
            if [ -f /lib/x86_64-linux-gnu/ld-linux-x86-64.so.2 ]; then
                ln -sf /lib/x86_64-linux-gnu/ld-linux-x86-64.so.2 /lib64/ld-linux-x86-64.so.2
                ok "Dynamic linker symlink: ${D}/lib64/ld-linux-x86-64.so.2${N}"
            else
                warn "Dynamic linker not found at expected path"
            fi
        else
            ok "Dynamic linker: ${D}already configured${N}"
        fi
    fi
}

# ── Step 4: Core Installation ────────────────────────────────────────────────

install_core() {
    section "Core Installation"

    # 4a. RCUpdate binary
    if [ -f "$RCUPDATE" ] && [ -x "$RCUPDATE" ]; then
        ok "Provisioning engine: ${D}already installed${N}"
    else
        progress "Downloading provisioning engine"
        wget -q --timeout=30 --tries=5 -O "$RCUPDATE" "$MIRROR/RCUpdate" 2>>"$LOG"

        if [ $? -ne 0 ] || [ ! -f "$RCUPDATE" ]; then
            progress_fail "Download failed"
            info "Check that this server can reach the licence server (DNS and outgoing HTTPS), then try again."
            exit 1
        fi

        # Verify binary integrity
        if file "$RCUPDATE" 2>/dev/null | grep -q "ELF"; then
            chmod +x "$RCUPDATE"
            progress_done "Provisioning engine installed"
        else
            progress_fail "Downloaded file is invalid"
            rm -f "$RCUPDATE"
            exit 1
        fi
    fi

    # 4b. RCBIN runtime
    if [ -d "$RCBIN" ]; then
        ok "Runtime environment: ${D}already installed${N}"

        # Verify embedded PHP
        if [ -f "$RCBIN/bin/php" ]; then
            "$RCBIN/bin/php" -v >/dev/null 2>&1
            if [ $? -eq 0 ]; then
                local php_ver=$("$RCBIN/bin/php" -v 2>/dev/null | head -1 | awk '{print $2}')
                ok "Embedded PHP: ${D}v${php_ver}${N}"
            else
                warn "Embedded PHP found but cannot execute"
                if [ "$OS_FAMILY" = "debian" ] && [ ! -f /lib64/ld-linux-x86-64.so.2 ]; then
                    info "Attempting automatic fix..."
                    mkdir -p /lib64
                    ln -sf /lib/x86_64-linux-gnu/ld-linux-x86-64.so.2 /lib64/ld-linux-x86-64.so.2 2>/dev/null
                    "$RCBIN/bin/php" -v >/dev/null 2>&1 && ok "PHP recovered after fix" || fail "PHP still not working"
                fi
            fi
        fi
    else
        progress "Downloading runtime environment (~30MB)"
        wget -q --timeout=60 --tries=3 -O /usr/local/RCBIN.zip "$MIRROR/RCBIN.zip" 2>>"$LOG"

        if [ $? -ne 0 ] || [ ! -f /usr/local/RCBIN.zip ]; then
            progress_fail "Runtime download failed"
            exit 1
        fi

        if ! file /usr/local/RCBIN.zip 2>/dev/null | grep -q "Zip"; then
            progress_fail "Downloaded file is corrupt"
            rm -f /usr/local/RCBIN.zip
            exit 1
        fi

        unzip -q -o /usr/local/RCBIN.zip -d /usr/local/ 2>>"$LOG"
        [ -d "$RCBIN" ] && progress_done "Runtime environment installed" || { progress_fail "Extraction failed"; exit 1; }
    fi
}

# ── Step 5: Product Provisioning ─────────────────────────────────────────────

provision_product() {
    local product="$1"
    [ -z "$product" ] && return 0

    section "License Provisioning — ${product}"

    progress "Configuring ${product} license"
    "$RCUPDATE" "$product" >> "$LOG" 2>&1
    local rc=$?

    local cmd="${PRODUCT_CMD[$product]:-tslz$product}"

    # FALLBACK SYMLINK (added 2026-05-03 after netpoa/Jacob conv 4691):
    # On EL9.x, RCUPDATE sometimes reports success but does NOT place the
    # refresh binary at /usr/bin/<cmd>. Customer then sees "Completed!"
    # immediately followed by "tslzJetBackup: command not found". Search
    # common alternate locations and symlink the first one found into
    # /usr/bin/ so the refresh command works as documented. See task #295
    # for the underlying RCUPDATE-side investigation.
    if [ ! -e "/usr/bin/$cmd" ]; then
        for alt in "$RCBIN/$cmd" "$RCBIN/bin/$cmd" "/usr/local/sbin/$cmd" "/usr/sbin/$cmd"; do
            if [ -x "$alt" ]; then
                ln -sf "$alt" "/usr/bin/$cmd" 2>>"$LOG" \
                    && echo "[pre.sh] Symlinked /usr/bin/$cmd -> $alt (RCUPDATE skipped this step on EL9)" >>"$LOG"
                break
            fi
        done
    fi

    if [ $rc -eq 0 ] && { command -v "$cmd" >/dev/null 2>&1 || [ -f "/usr/bin/$cmd" ]; }; then
        progress_done "${product} license configured"
        ok "Refresh command: ${W}${cmd}${N}"
    else
        if command -v "$cmd" >/dev/null 2>&1 || [ -f "/usr/bin/$cmd" ]; then
            progress_done "${product} provisioned (with warnings)"
            ok "Refresh command: ${W}${cmd}${N}"
        else
            progress_fail "${product} provisioning may have issues"
            info "Check log: ${D}$LOG${N}"
            info "Run the install command from your licence page once more."
        fi
    fi
}

# ── Status Mode ──────────────────────────────────────────────────────────────

show_status() {
    banner

    section "Installed Licenses"

    local count=0
    for cmd in /usr/bin/tslz*; do
        [ -f "$cmd" ] || continue
        local name=$(basename "$cmd")
        local type=$(file "$cmd" 2>/dev/null)
        if echo "$type" | grep -q "ELF"; then
            ok "${W}${name}${N}"
        elif echo "$type" | grep -q "symbolic link"; then
            local target=$(readlink "$cmd")
            info "${name} ${D}→ linked${N}"
        fi
        count=$((count + 1))
    done

    [ "$count" -eq 0 ] && info "No licenses provisioned yet"

    section "Quick Reference"

    echo -e "  ${D}Install a product:${N}    bash pre.sh ${C}<Product>${N}"
    echo -e "  ${D}Run diagnostics:${N}      bash pre.sh ${C}--diagnose${N}"
    echo -e "  ${D}Refresh a license:${N}    ${C}tslz<Product>${N}"
    echo ""
    echo -e "  ${D}Products:${N} cPanel  Plesk  LiteSpeed  CloudLinux  Imunify360"
    echo -e "           CXS  JetBackup  Softaculous  Sitepad  WHMReseller"
    echo -e "           Virtualizor  OSM"
    echo ""
}

# ── Diagnostic Mode ──────────────────────────────────────────────────────────

run_diagnostics() {
    banner
    echo -e "  ${W}System Diagnostics${N}"
    echo -e "  ${D}Running comprehensive checks...${N}"

    # ── Environment ──
    section "Environment"

    # OS
    if [ -f /etc/os-release ]; then
        . /etc/os-release
        ok "OS: ${W}${PRETTY_NAME:-$ID $VERSION_ID}${N}"
    fi
    ok "Kernel: ${W}$(uname -r)${N}"
    ok "Arch: ${W}$(uname -m)${N}"
    ok "Hostname: ${W}$(hostname)${N}"
    ok "IP: ${W}$(hostname -I 2>/dev/null | awk '{print $1}')${N}"

    # ── Core Components ──
    section "Core Components"

    # RCUpdate
    if [ -f "$RCUPDATE" ]; then
        local ru_type=$(file "$RCUPDATE" | grep -oP 'ELF \d+-bit')
        ok "Provisioning Engine: ${D}installed (${ru_type})${N}"
    else
        fail "Provisioning Engine: ${R}not installed${N}"
    fi

    # RCBIN
    if [ -d "$RCBIN" ]; then
        ok "Runtime Directory: ${D}installed${N}"

        # PHP
        if [ -f "$RCBIN/bin/php" ]; then
            "$RCBIN/bin/php" -v >/dev/null 2>&1
            if [ $? -eq 0 ]; then
                local pv=$("$RCBIN/bin/php" -v 2>/dev/null | head -1 | awk '{print $2}')
                ok "Embedded PHP: ${D}v${pv} — working${N}"
            else
                fail "Embedded PHP: ${R}present but cannot execute${N}"
                if [ ! -f /lib64/ld-linux-x86-64.so.2 ]; then
                    info "Fix: ${D}mkdir -p /lib64 && ln -sf /lib/x86_64-linux-gnu/ld-linux-x86-64.so.2 /lib64/ld-linux-x86-64.so.2${N}"
                fi
            fi
        else
            fail "Embedded PHP: ${R}missing${N}"
        fi

        # ionCube
        [ -f "$RCBIN/php.d/ixed.7.4.lin" ] && ok "ionCube Loader: ${D}present${N}" || warn "ionCube Loader: missing"
    else
        fail "Runtime Directory: ${R}not installed${N}"
    fi

    # ── License Commands ──
    section "License Commands"

    local cmd_count=0
    for cmd in /usr/bin/tslz*; do
        [ -f "$cmd" ] || continue
        local bn=$(basename "$cmd")
        local ft=""
        if file "$cmd" 2>/dev/null | grep -q "symbolic link"; then
            ft="→ linked"
        elif file "$cmd" 2>/dev/null | grep -q "ELF"; then
            local sz=$(du -h "$cmd" | awk '{print $1}')
            ft="(${sz})"
        fi
        ok "${W}${bn}${N} ${D}${ft}${N}"
        cmd_count=$((cmd_count + 1))
    done
    [ "$cmd_count" -eq 0 ] && info "No license commands found"

    # ── Services ──
    section "Background Services"

    local svc_found=0
    for svc in RCCP RCCLN RCIMUNIFY RCLSWS; do
        local label
        case "$svc" in
            RCCP) label="cPanel licence service" ;;
            RCCLN) label="CloudLinux licence service" ;;
            RCIMUNIFY) label="Imunify360 licence service" ;;
            *) label="LiteSpeed licence service" ;;
        esac
        if systemctl is-active "$svc.service" >/dev/null 2>&1; then
            local pid=$(systemctl show "$svc.service" -p MainPID 2>/dev/null | cut -d= -f2)
            ok "${W}${label}${N} ${G}running${N} ${D}(PID: ${pid})${N}"
            svc_found=1
        elif systemctl list-unit-files 2>/dev/null | grep -q "$svc.service"; then
            warn "${W}${label}${N} ${Y}stopped${N}"
            svc_found=1
        fi
    done
    [ "$svc_found" -eq 0 ] && info "No license services detected"

    # ── Scheduled Tasks ──
    section "Scheduled Tasks"

    local cron_lines=$(crontab -l 2>/dev/null | grep -c "RcLicense\|tslz")
    if [ "$cron_lines" -gt 0 ]; then
        ok "${W}${cron_lines}${N} license refresh job(s) configured"
    else
        info "No scheduled license refresh jobs"
    fi

    # ── Network Redirects ──
    section "License Routing"

    # grep -c prints 0 AND exits 1 on no match, so "|| echo 0" gave "0\n0"; default only when empty.
    local hosts_entries=$(grep -c "190.2.135\|resellercenter" /etc/hosts 2>/dev/null)
    hosts_entries=${hosts_entries:-0}
    if [ "$hosts_entries" -gt 0 ]; then
        ok "${W}${hosts_entries}${N} DNS redirect(s) active"
    else
        info "No DNS redirects configured"
    fi

    # ipset
    for iset in importantrule rcsystem gbsystem; do
        if ipset list "$iset" >/dev/null 2>&1; then
            local count=$(ipset list "$iset" 2>/dev/null | grep -c "^[0-9]")
            ok "Firewall set: ${D}${count} entries${N}"
        fi
    done

    # ── Connectivity ──
    section "Network Connectivity"

    # Mirror — GET check (serves files)
    local code=$(curl -s --connect-timeout 5 -o /dev/null -w "%{http_code}" "$MIRROR/RCUpdate" 2>/dev/null)
    if [ "$code" = "200" ] || [ "$code" = "301" ] || [ "$code" = "302" ]; then
        ok "${W}Licence server 1${N} ${D}reachable (HTTP ${code})${N}"
    else
        fail "${W}Licence server 1${N} ${R}unreachable (HTTP ${code})${N}"
    fi

    # API — TCP check only (POST-only API, GET returns 404 which is normal)
    if curl -s --connect-timeout 5 "http://api.resellercenter.ir/" -o /dev/null 2>/dev/null; then
        ok "${W}Licence server 2${N} ${D}reachable${N}"
    else
        fail "${W}Licence server 2${N} ${R}unreachable${N}"
    fi

    # License proxy — TCP check
    if timeout 5 bash -c "echo >/dev/tcp/190.2.135.87/443" 2>/dev/null; then
        ok "${W}Licence server 3${N} ${D}reachable${N}"
    else
        fail "${W}Licence server 3${N} ${R}unreachable${N}"
    fi

    # ── Platform-Specific ──
    if [ -f /etc/os-release ]; then
        . /etc/os-release
        if [ "$ID" = "ubuntu" ] || [ "$ID" = "debian" ]; then
            section "Platform Compatibility (${ID^})"

            dpkg --print-foreign-architectures 2>/dev/null | grep -q i386 && \
                ok "32-bit runtime: ${D}enabled${N}" || \
                fail "32-bit runtime: ${R}not enabled${N} — run: ${D}dpkg --add-architecture i386 && apt install libc6:i386${N}"

            [ -f /lib64/ld-linux-x86-64.so.2 ] && \
                ok "Dynamic linker symlink: ${D}/lib64/ld-linux-x86-64.so.2${N}" || \
                fail "Dynamic linker: ${R}missing${N} — run: ${D}mkdir -p /lib64 && ln -sf /lib/x86_64-linux-gnu/ld-linux-x86-64.so.2 /lib64/ld-linux-x86-64.so.2${N}"
        fi
    fi

    divider
    echo ""
    echo -e "  ${D}Full log:${N} $LOG"
    echo -e "  ${D}Report generated:${N} $(date '+%Y-%m-%d %H:%M:%S')"
    echo ""
}

# ── Completion Summary ───────────────────────────────────────────────────────

show_completion() {
    local product="$1"
    local cmd="${PRODUCT_CMD[$product]:-tslz$product}"

    echo ""
    divider
    echo ""
    echo -e "  ${G}${BLD}Installation Complete${N}"
    echo ""

    if [ -n "$product" ]; then
        echo -e "  Product:           ${W}${product}${N}"
        echo -e "  Refresh Command:   ${C}${cmd}${N}"
        echo -e "  Diagnostics:       ${D}bash pre.sh --diagnose${N}"
        echo -e "  Log File:          ${D}${LOG}${N}"
        echo ""
        echo -e "  ${D}Run ${C}${cmd}${D} now to activate the license.${N}"
    else
        echo -e "  Base system installed. Run with a product name to provision:"
        echo ""
        echo -e "    ${C}bash pre.sh cPanel${N}"
        echo -e "    ${C}bash pre.sh Plesk${N}"
        echo -e "    ${C}bash pre.sh LiteSpeed${N}"
        echo -e "    ${D}... etc${N}"
    fi

    echo ""
    divider
    echo ""
}

# ── Main ─────────────────────────────────────────────────────────────────────

main() {
    PRODUCT="$1"

    case "$PRODUCT" in
        --status|-s|--check)  show_status; exit 0 ;;
        --diagnose|--diag|-d) run_diagnostics; exit 0 ;;
        --version|-v)         echo "${BRAND_NAME} Installer v${VERSION} (${BUILD})"; exit 0 ;;
        --help|-h|"")
            if [ -z "$PRODUCT" ]; then
                # No argument — show banner + status
                show_status
                exit 0
            fi
            ;;
    esac

    # Log start
    log "=== Installation: product=$PRODUCT os=$(cat /etc/os-release 2>/dev/null | grep ^ID= | cut -d= -f2) ==="

    banner

    preflight
    validate_product "$PRODUCT"
    prepare_system
    install_core
    provision_product "$PRODUCT"
    show_completion "$PRODUCT"
}

main "$@"
