#!/bin/bash

#############################################################################
# Server Management Toolkit - BETA/DEV Version
# Version: 2.1-beta
#
# Development and testing version - SEPARATE FROM PRODUCTION
# Uses independent cache, config, and data directories
#############################################################################

set -eo pipefail

# Check if running in interactive mode
if [[ $- != *i* ]]; then
    # Non-interactive mode - set flag for read operations
    INTERACTIVE_MODE=0
else
    INTERACTIVE_MODE=1
fi

# Configuration
SUITE_VERSION="2.1.0-BETA"
BASE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
MODULES_DIR="$BASE_DIR/modules"
LIB_DIR="$BASE_DIR/lib"
CONFIG_DIR="$BASE_DIR/config"

# Load core libraries
source "$LIB_DIR/common-functions.sh" || { echo "ERROR: Failed to load common-functions.sh"; return 1; }
source "$LIB_DIR/system-detect.sh" || { echo "ERROR: Failed to load system-detect.sh"; return 1; }
source "$LIB_DIR/log-paths.sh" || { echo "ERROR: Failed to load log-paths.sh"; return 1; }
source "$LIB_DIR/database-paths.sh" || { echo "ERROR: Failed to load database-paths.sh"; return 1; }
source "$LIB_DIR/service-info.sh" || { echo "ERROR: Failed to load service-info.sh"; return 1; }
source "$LIB_DIR/control-panel-paths.sh" || { echo "ERROR: Failed to load control-panel-paths.sh"; return 1; }
source "$LIB_DIR/web-server-config.sh" || { echo "ERROR: Failed to load web-server-config.sh"; return 1; }
source "$LIB_DIR/firewall-operations.sh" || { echo "ERROR: Failed to load firewall-operations.sh"; return 1; }
source "$LIB_DIR/security-tools.sh" || { echo "ERROR: Failed to load security-tools.sh"; return 1; }
source "$LIB_DIR/system-authentication.sh" || { echo "ERROR: Failed to load system-authentication.sh"; return 1; }
source "$LIB_DIR/system-variables.sh" || { echo "ERROR: Failed to load system-variables.sh"; return 1; }
source "$LIB_DIR/domain-discovery.sh" || { echo "ERROR: Failed to load domain-discovery.sh"; return 1; }
source "$LIB_DIR/user-manager.sh" || { echo "ERROR: Failed to load user-manager.sh"; return 1; }
source "$LIB_DIR/reference-db.sh" || { echo "ERROR: Failed to load reference-db.sh"; return 1; }
source "$LIB_DIR/menu-functions.sh" || { echo "ERROR: Failed to load menu-functions.sh"; return 1; }

# Color codes
RED='\033[0;31m'
YELLOW='\033[1;33m'
GREEN='\033[0;32m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
MAGENTA='\033[0;35m'
BOLD='\033[1m'
NC='\033[0m'

# Banner
show_banner() {
    clear
    echo "═══════════════════════════════════════════════════════════════"
    echo "     ⚠️  Server Management Toolkit v${SUITE_VERSION}"
    echo "     🧪 BETA/DEV VERSION - Testing & Development"
    echo "     Complete cPanel/Linux Server Administration Suite"
    echo "═══════════════════════════════════════════════════════════════"
    echo "     ⚠️  This is a SEPARATE INSTANCE from production"
    echo ""
}

# Run a module
run_module() {
    local category="$1"
    local module="$2"
    shift 2

    if [ ! -f "$MODULES_DIR/$category/$module" ]; then
        echo ""
        echo -e "✗ Module not found: $category/$module"
        echo ""
        if ! read -p "Press Enter to continue..." </dev/tty 2>/dev/null; then
            true  # Continue even if read fails
        fi
        return 1
    fi

    echo ""
    echo -e "Launching: $category/$module"
    echo -e "──────────────────────────────────────────────────────────────"

    # Run module directly - keep SYS_ variables cached for performance
    # Modules will use cached detection instead of re-detecting on every run
    "$MODULES_DIR/$category/$module" "$@"
    local exit_code=$?

    echo ""
    echo -e "──────────────────────────────────────────────────────────────"
    if [ "${exit_code:-0}" -eq 0 ]; then
        echo -e "✓ Completed successfully"
    else
        echo -e "✗ Exited with code: $exit_code"
    fi
    echo ""
    if ! read -p "Press Enter to continue..." </dev/tty 2>/dev/null; then
        true  # Continue even if read fails
    fi
}

#############################################################################
# SYSTEM INFO DISPLAY (Quick View)
#############################################################################

show_system_overview() {
    # Only show if detection is complete
    if [ -z "${SYS_DETECTION_COMPLETE:-}" ]; then
        return
    fi

    echo ""
    echo "🖥️  System Information:"

    # Control Panel
    if [ "$SYS_CONTROL_PANEL" != "none" ]; then
        echo -n "  Control Panel: ${SYS_CONTROL_PANEL^^}"
        [ -n "$SYS_CONTROL_PANEL_VERSION" ] && echo -n " v${SYS_CONTROL_PANEL_VERSION}" || echo -n " (version unknown)"
        echo ""
    else
        echo "  Control Panel: Standalone (no control panel)"
    fi

    # OS
    echo "  OS: ${SYS_OS_TYPE^^} ${SYS_OS_VERSION}"
    [ "${SYS_CLOUDLINUX:-}" = "yes" ] && echo "  ➜ CloudLinux detected"

    # Web Server
    echo -n "  Web Server: ${SYS_WEB_SERVER^^}"
    [ -n "$SYS_WEB_SERVER_VERSION" ] && echo " v${SYS_WEB_SERVER_VERSION}" || echo ""

    # Database
    if [ "$SYS_DB_TYPE" != "none" ]; then
        echo -n "  Database: ${SYS_DB_TYPE^^}"
        [ -n "$SYS_DB_VERSION" ] && echo " v${SYS_DB_VERSION}" || echo ""
    fi

    # PHP Versions
    if [ ${#SYS_PHP_VERSIONS[@]} -gt 0 ]; then
        echo -n "  PHP Versions: "
        local php_list=$(printf '%s, ' "${SYS_PHP_VERSIONS[@]}")
        echo "${php_list%, }"
    fi

    # Firewall
    if [ "$SYS_FIREWALL" != "none" ]; then
        echo -n "  Firewall: ${SYS_FIREWALL^^}"
        [ "$SYS_FIREWALL_ACTIVE" = "yes" ] && echo " (active)" || echo " (inactive)"
    fi

    # Cloudflare
    [ "$SYS_CLOUDFLARE_ACTIVE" = "yes" ] && echo "  Cloudflare: Detected"

    echo ""
}

#############################################################################
# MAIN MENU
#############################################################################

show_main_menu() {
    show_banner

    # Show quick system overview if detection is complete
    [ -n "${SYS_DETECTION_COMPLETE:-}" ] && show_system_overview

    menu_header "Server Management Toolkit"

    menu_section "Quick Diagnostics"
    menu_option 1 "System Health Check" "Full server diagnostics"

    echo ""
    menu_section "Main Categories"
    menu_option 2 "Security & Monitoring"
    menu_option 3 "Website Diagnostics"
    menu_option 4 "Performance & Maintenance"
    menu_option 5 "Backup & Recovery"
    menu_option 6 "Email Troubleshooting"

    echo ""
    menu_section "System"
    menu_option 7 "Cleanup Toolkit Data" "Clear cached data"

    echo ""
    menu_exit
    menu_divider

    read_menu_choice "Select option" 0 7
}

#############################################################################
# SECURITY & MONITORING
#############################################################################

#############################################################################
# SECURITY SUB-MENUS
#############################################################################

# Threat Analysis Sub-Menu
show_threat_analysis_menu() {
    show_banner
    menu_header "Threat Analysis"

    menu_option 1 "Bot & Traffic Analyzer" "Full analysis (all logs)"
    menu_option 2 "Quick Scan (1 hour)" "Recent activity only"
    menu_option 3 "IP Reputation Manager" "Query/manage IP database"
    menu_option 4 "Suspicious Login Monitor" "SSH/Panel login analysis"
    menu_option 5 "Malware Scanner" "ImunifyAV, ClamAV, Maldet"
    menu_option 6 "Historical Attack Analysis" "Scan past logs (ET Open)"

    echo ""
    menu_back "Security Menu"
    menu_divider

    read_menu_choice "Select option" 0 6
}

handle_threat_analysis_menu() {
    if [ "$INTERACTIVE_MODE" -eq 0 ]; then
        return 0  # Non-interactive mode, exit
    fi

    while true; do
        show_threat_analysis_menu

        case "$MENU_CHOICE" in
            1) run_module "security" "bot-analyzer.sh" ;;
            2) run_module "security" "bot-analyzer.sh" -H 1 ;;
            3) run_module "security" "ip-reputation-manager.sh" ;;
            4) run_module "security" "suspicious-login-monitor.sh" ;;
            5) run_module "security" "malware-scanner.sh" ;;
            6) bash "$BASE_DIR/tools/analyze-historical-attacks.sh" ;;
            0) return ;;
            *) menu_invalid_choice ;;
        esac
    done
}

# Live Monitoring Sub-Menu
show_live_monitoring_menu() {
    show_banner
    menu_header "Live Monitoring"

    menu_option 1 "Live Attack Monitor" "Unified threat intelligence"
    menu_option 2 "SSH Attack Monitor" "SSH brute force detection"
    menu_option 3 "Web Traffic Monitor" "HTTP attack detection"
    menu_option 4 "Firewall Activity Monitor" "CSF/iptables monitoring"

    echo ""
    menu_back "Security Menu"
    menu_divider

    read_menu_choice "Select option" 0 4
}

handle_live_monitoring_menu() {
    if [ "$INTERACTIVE_MODE" -eq 0 ]; then
        return 0  # Non-interactive mode, exit
    fi

    while true; do
        show_live_monitoring_menu

        case "$MENU_CHOICE" in
            1) run_module "security" "live-attack-monitor.sh" ;;
            2) run_module "security" "ssh-attack-monitor.sh" ;;
            3) run_module "security" "web-traffic-monitor.sh" ;;
            4) run_module "security" "firewall-activity-monitor.sh" ;;
            0) return ;;
            *) menu_invalid_choice ;;
        esac
    done
}

# Log Viewers Sub-Menu
show_log_viewers_menu() {
    show_banner
    menu_header "Log Viewers"

    menu_option 1 "Apache Access Log" "Live web access"
    menu_option 2 "Apache Error Log" "Live web errors"
    menu_option 3 "Mail Log" "Live email activity"
    menu_option 4 "Security Log" "Live auth attempts"

    echo ""
    menu_back "Security Menu"
    menu_divider

    read_menu_choice "Select option" 0 4
}

handle_log_viewers_menu() {
    if [ "$INTERACTIVE_MODE" -eq 0 ]; then
        return 0  # Non-interactive mode, exit
    fi

    while true; do
        show_log_viewers_menu

        case "$MENU_CHOICE" in
            1) run_module "security" "tail-apache-access.sh" ;;
            2) run_module "security" "tail-apache-error.sh" ;;
            3) run_module "security" "tail-mail-log.sh" ;;
            4) run_module "security" "tail-secure-log.sh" ;;
            0) return ;;
            *) menu_invalid_choice ;;
        esac
    done
}

# Security Actions Sub-Menu
show_security_actions_menu() {
    show_banner
    menu_header "Security Actions"

    menu_option 1 "Enable cPHulk Protection" "Brute force protection"
    menu_option 2 "Optimize CT_LIMIT" "Connection tracking tuning"
    menu_option 3 "Block Malicious Bots" "User-Agent blocking (Apache)"

    echo ""
    menu_back "Security Menu"
    menu_divider

    read_menu_choice "Select option" 0 3
}

handle_security_actions_menu() {
    if [ "$INTERACTIVE_MODE" -eq 0 ]; then
        return 0  # Non-interactive mode, exit
    fi

    while true; do
        show_security_actions_menu

        case "$MENU_CHOICE" in
            1) run_module "security" "enable-cphulk.sh" ;;
            2) run_module "security" "optimize-ct-limit.sh" ;;
            3) run_module "security" "bot-blocker.sh" ;;
            0) return ;;
            *) menu_invalid_choice ;;
        esac
    done
}

#############################################################################
# MAIN SECURITY MENU
#############################################################################

show_security_menu() {
    show_banner
    menu_header "Security & Monitoring"

    menu_option 1 "Threat Analysis" "Analyze threats & reputation"
    menu_option 2 "Live Monitoring" "Real-time attack detection"
    menu_option 3 "Log Viewers" "Tail system/security logs"
    menu_option 4 "Security Actions" "Hardening & protection"

    echo ""
    menu_back "Main Menu"
    menu_divider

    read_menu_choice "Select option" 0 4
}

handle_security_menu() {
    if [ "$INTERACTIVE_MODE" -eq 0 ]; then
        return 0  # Non-interactive mode, exit
    fi

    while true; do
        show_security_menu

        case "$MENU_CHOICE" in
            1) handle_threat_analysis_menu ;;
            2) handle_live_monitoring_menu ;;
            3) handle_log_viewers_menu ;;
            4) handle_security_actions_menu ;;
            0) return ;;
            *) menu_invalid_choice ;;
        esac
    done
}

#############################################################################
# WEBSITE DIAGNOSTICS
#############################################################################

show_website_menu() {
    show_banner
    menu_header "Website Diagnostics"

    menu_section "Error Analysis"
    menu_option 1 "Website Error Analyzer" "Find 500/config errors"
    menu_option 2 "Fast 500 Error Tracker" "ONLY 500s + root cause"

    echo ""
    menu_section "Performance & Slowness"
    menu_option 3 "Website Slowness Diagnostics" "Multi-framework analysis"

    echo ""
    menu_section "WordPress Management"
    menu_option 4 "WordPress Tools" "WP-Cron manager & tools"

    echo ""
    menu_section "Domain Analysis"
    menu_option 5 "Cloudflare Detector" "Domains using Cloudflare"

    echo ""
    menu_back "Main Menu"
    menu_divider

    read_menu_choice "Select option" 0 5
}

handle_website_menu() {
    if [ "$INTERACTIVE_MODE" -eq 0 ]; then
        return 0  # Non-interactive mode, exit
    fi

    while true; do
        show_website_menu

        case "$MENU_CHOICE" in
            1) run_module "website" "website-error-analyzer.sh" ;;
            2) run_module "website" "500-error-tracker.sh" ;;
            3) run_module "website" "website-slowness-diagnostics.sh" ;;
            4) bash "$MODULES_DIR/website/wordpress-menu.sh" ;;
            5) run_module "website" "cloudflare-detector.sh" ;;
            0) return ;;
            *) menu_invalid_choice ;;
        esac
    done
}

#############################################################################
# PERFORMANCE ANALYSIS
#############################################################################

show_performance_menu() {
    show_banner
    menu_header "Performance & Maintenance"

    menu_section "Database"
    menu_option 1 "MySQL Query Analyzer" "Find slow queries & optimize"

    echo ""
    menu_section "Network & Resources"
    menu_option 2 "Network & Bandwidth" "Traffic & top consumers"
    menu_option 3 "Hardware Health Check" "SMART, memory, CPU sensors"

    echo ""
    menu_section "PHP Optimization"
    menu_option 4 "PHP Configuration Optimizer" "Per-domain PHP tuning"

    echo ""
    menu_section "System Health"
    menu_option 5 "Loadwatch Health Analyzer" "Historical system analysis"
    menu_option 6 "Disk Space Analyzer" "Find space issues"

    echo ""
    menu_section "Caching Solutions"
    menu_option 7 "Nginx + Varnish Manager" "Setup/manage caching stack"

    echo ""
    menu_back "Main Menu"
    menu_divider

    read_menu_choice "Select option" 0 7
}

handle_performance_menu() {
    if [ "$INTERACTIVE_MODE" -eq 0 ]; then
        return 0  # Non-interactive mode, exit
    fi

    while true; do
        show_performance_menu

        case "$MENU_CHOICE" in
            1) run_module "performance" "mysql-query-analyzer.sh" ;;
            2) run_module "performance" "network-bandwidth-analyzer.sh" ;;
            3) run_module "performance" "hardware-health-check.sh" ;;
            4) run_module "performance" "php-optimizer.sh" ;;
            5) handle_loadwatch_analyzer ;;
            6) run_module "maintenance" "disk-space-analyzer.sh" ;;
            7) run_module "performance" "nginx-varnish-manager.sh" ;;
            0) return ;;
            *) menu_invalid_choice ;;
        esac
    done
}

handle_loadwatch_analyzer() {
    if [ "$INTERACTIVE_MODE" -eq 0 ]; then
        return 0  # Non-interactive mode, exit
    fi

    show_banner
    menu_header "Loadwatch Health Analyzer"

    menu_section "Select time range for analysis"
    menu_option 1 "Last 1 Hour" "Recent activity"
    menu_option 2 "Last 6 Hours" "Mid-term trending"
    menu_option 3 "Last 24 Hours" "Full day analysis"
    menu_option 4 "Last 7 Days" "Weekly patterns"
    menu_option 5 "Last 30 Days" "Monthly overview"

    echo ""
    menu_back "Performance Menu"
    menu_divider

    read_menu_choice "Select time range" 0 5

    case "$MENU_CHOICE" in
        1) run_module "diagnostics" "loadwatch-analyzer.sh" "-r" "1h" ;;
        2) run_module "diagnostics" "loadwatch-analyzer.sh" "-r" "6h" ;;
        3) run_module "diagnostics" "loadwatch-analyzer.sh" "-r" "24h" ;;
        4) run_module "diagnostics" "loadwatch-analyzer.sh" "-r" "7d" ;;
        5) run_module "diagnostics" "loadwatch-analyzer.sh" "-r" "30d" ;;
        0) return ;;
        *) menu_invalid_choice ;;
    esac
}

#############################################################################
# BACKUP & RECOVERY
#############################################################################

show_backup_menu() {
    show_banner
    menu_header "Backup & Recovery"

    menu_section "Acronis Cyber Protect"
    menu_option 1 "Acronis Management" "Complete backup management"

    echo ""
    menu_section "Database Tools"
    menu_option 2 "MySQL File Restore" "Convert restored DB files"

    echo ""
    menu_section "Maintenance"
    menu_option 3 "Cleanup Toolkit Data" "Remove temp files"

    echo ""
    menu_back "Main Menu"
    menu_divider

    read_menu_choice "Select option" 0 3
}

show_acronis_menu() {
    show_banner
    menu_header "Acronis Cyber Protect"

    menu_section "Installation & Setup"
    menu_option 1 "Install Acronis Agent" "Download and install"
    menu_option 2 "Register with Cloud" "Connect to Acronis Cloud"
    menu_option 3 "Configure Agent" "Adjust settings"

    echo ""
    menu_section "Backup Management"
    menu_option 4 "Manage Backups" "Complete backup interface"

    echo ""
    menu_section "Status & Monitoring"
    menu_option 5 "Check Agent Status" "Verify Acronis running"
    menu_option 6 "View Logs" "Check Acronis logs"
    menu_option 7 "Troubleshoot" "Diagnose backup failures"

    echo ""
    menu_section "Maintenance"
    menu_option 8 "Update Agent" "Upgrade to latest version"
    menu_option 9 "Uninstall Acronis" "Remove agent"

    echo ""
    menu_back "Backup Menu"
    menu_divider

    read_menu_choice "Select option" 0 9
}

handle_backup_menu() {
    if [ "$INTERACTIVE_MODE" -eq 0 ]; then
        return 0  # Non-interactive mode, exit
    fi

    while true; do
        show_backup_menu

        case "$MENU_CHOICE" in
            1) handle_acronis_menu ;;
            2) run_module "backup" "mysql-restore-to-sql.sh" ;;
            3) run_module "maintenance" "cleanup-toolkit-data.sh" ;;
            0) return ;;
            *) menu_invalid_choice ;;
        esac
    done
}

handle_acronis_menu() {
    if [ "$INTERACTIVE_MODE" -eq 0 ]; then
        return 0  # Non-interactive mode, exit
    fi

    while true; do
        show_acronis_menu

        case "$MENU_CHOICE" in
            1) run_module "backup" "acronis-install.sh" ;;
            2) run_module "backup" "acronis-register.sh" ;;
            3) run_module "backup" "acronis-configure.sh" ;;
            4) run_module "backup" "acronis-backup-manager.sh" ;;
            5) run_module "backup" "acronis-agent-status.sh" ;;
            6) run_module "backup" "acronis-logs.sh" ;;
            7) run_module "backup" "acronis-troubleshoot.sh" ;;
            8) run_module "backup" "acronis-update.sh" ;;
            9) run_module "backup" "acronis-uninstall.sh" ;;
            0) return ;;
            *) menu_invalid_choice ;;
        esac
    done
}

#############################################################################
# EMAIL TROUBLESHOOTING & MAINTENANCE
#############################################################################

show_email_menu() {
    show_banner
    menu_header "Email Troubleshooting & Maintenance"

    menu_section "Diagnostics"
    menu_option 1 "Email Diagnostics" "Verify email/domain working"
    menu_option 2 "Email Deliverability Test" "Test sending/receiving"
    menu_option 3 "Mail Queue Inspector" "View stuck emails"
    menu_option 4 "SMTP Connection Test" "Verify mail server"
    menu_option 5 "SPF/DKIM/DMARC Check" "Email authentication"

    echo ""
    menu_section "Troubleshooting"
    menu_option 6 "Blacklist Check" "Check IP reputation"
    menu_option 7 "Mail Log Analyzer" "Search mail logs"
    menu_option 8 "Flush Mail Queue" "Clear stuck emails"

    echo ""
    menu_section "Maintenance"
    menu_option 9 "Clean Mailboxes" "Remove old emails"
    menu_option 10 "Mailbox Size Report" "Show usage per account"

    echo ""
    menu_back "Main Menu"
    menu_divider

    read_menu_choice "Select option" 0 10
}

handle_email_menu() {
    if [ "$INTERACTIVE_MODE" -eq 0 ]; then
        return 0  # Non-interactive mode, exit
    fi

    while true; do
        show_email_menu

        case "$MENU_CHOICE" in
            1) run_module "email" "email-diagnostics.sh" ;;
            2) run_module "email" "deliverability-test.sh" ;;
            3) run_module "email" "mail-queue-inspector.sh" ;;
            4) run_module "email" "smtp-connection-test.sh" ;;
            5) run_module "email" "spf-dkim-dmarc-check.sh" ;;
            6) run_module "email" "blacklist-check.sh" ;;
            7) run_module "email" "mail-log-analyzer.sh" ;;
            8) run_module "email" "flush-mail-queue.sh" ;;
            9) run_module "email" "clean-mailboxes.sh" ;;
            10) run_module "email" "mailbox-size-report.sh" ;;
            0) return ;;
            *) menu_invalid_choice ;;
        esac
    done
}

#############################################################################
# INITIALIZATION
#############################################################################

init_directories() {
    mkdir -p "$MODULES_DIR"/{security,website,performance,backup,diagnostics,maintenance,email} || {
        echo "ERROR: Failed to create module directories"; return 1
    }
    mkdir -p "$LIB_DIR" "$CONFIG_DIR" "$BASE_DIR/logs" || {
        echo "ERROR: Failed to create base directories"; return 1
    }
    touch "$CONFIG_DIR/whitelist-ips.txt" 2>/dev/null || true
    touch "$CONFIG_DIR/whitelist-user-agents.txt" 2>/dev/null || true
}

startup_detection() {
    # Auto-clear cache if toolkit files are newer (fresh git pull)
    # This ensures users always get fresh data after git updates
    if [ -f "$BASE_DIR/.sysref.beta" ] && [ -f "$BASE_DIR/launcher.sh" ]; then
        if [ "$BASE_DIR/launcher.sh" -nt "$BASE_DIR/.sysref.beta" ]; then
            rm -f "$BASE_DIR/.sysref.beta" "$BASE_DIR/.sysref.beta.timestamp" 2>/dev/null || true
        fi
    fi

    # Also check production cache name for backward compatibility
    if [ -f "$BASE_DIR/.sysref" ] && [ -f "$BASE_DIR/launcher.sh" ]; then
        if [ "$BASE_DIR/launcher.sh" -nt "$BASE_DIR/.sysref" ]; then
            rm -f "$BASE_DIR/.sysref" "$BASE_DIR/.sysref.timestamp" 2>/dev/null || true
        fi
    fi

    # Initialize system detection first (required for show_system_overview)
    if [ -z "${SYS_DETECTION_COMPLETE:-}" ]; then
        initialize_system_detection
    fi

    if ! db_is_fresh; then
        clear
        print_banner "Server Management Toolkit - Initializing"
        echo ""
        print_info "Detecting server configuration..."
        echo ""

        build_reference_database

        echo ""
        print_section "Detection Summary"
        echo ""

        echo -e "System:"
        echo "  Control Panel: $SYS_CONTROL_PANEL $SYS_CONTROL_PANEL_VERSION"
        echo "  OS: $SYS_OS_TYPE $SYS_OS_VERSION"
        echo "  Web Server: $SYS_WEB_SERVER $SYS_WEB_SERVER_VERSION"
        echo "  Database: $SYS_DB_TYPE $SYS_DB_VERSION"
        echo ""

        # Count records in database with single awk pass (instead of 4 separate grep -c calls)
        local counts=$(awk -F'|' '{a[$1]++} END {printf "%d %d %d %d", a["USER"]+0, a["DOMAIN"]+0, a["DB"]+0, a["WP"]+0}' "$SYSREF_DB" 2>/dev/null || echo "0 0 0 0")
        read -r user_count domain_count db_count wp_count <<< "$counts"

        echo -e "Server Content:"
        echo "  Users: $user_count"
        echo "  Domains: $domain_count"
        echo "  Databases: $db_count"
        echo "  WordPress Sites: $wp_count"
        echo ""

        print_success "Detection complete! Cached for 1 hour."
        echo ""

        # Read from terminal (use /dev/tty directly)
        if ! read -p "Press Enter to continue..." </dev/tty 2>/dev/null; then
            true  # Continue even if read fails
        fi
    else
        # Database is cached and fresh, but still ensure detection was completed
        # (this addresses issue where detection output not shown on cached runs)
        if [ -z "${SYS_DETECTION_COMPLETE:-}" ]; then
            print_error "System detection failed - please check system configuration"
            return 1
        fi
    fi
}

#############################################################################
# MAIN LOOP
#############################################################################

main() {
    # Handle command-line arguments
    case "${1:-}" in
        --detect-only|--check-detection)
            # Initialize directories
            init_directories || {
                echo "ERROR: Failed to initialize directories"
                return 1
            }

            # Force fresh detection regardless of cache
            echo "Forcing system re-detection..."
            echo ""
            rm -f "$BASE_DIR/.sysref.beta" "$BASE_DIR/.sysref.beta.timestamp" 2>/dev/null || true

            # Run detection
            initialize_system_detection

            # Show results
            echo ""
            echo "═══════════════════════════════════════════════════════════════"
            echo "                    DETECTION RESULTS"
            echo "═══════════════════════════════════════════════════════════════"
            echo ""
            echo "Control Panel:      ${SYS_CONTROL_PANEL:-unknown} ${SYS_CONTROL_PANEL_VERSION:-}"
            echo "Operating System:   ${SYS_OS_TYPE:-unknown} ${SYS_OS_VERSION:-}"
            echo "Web Server:         ${SYS_WEB_SERVER:-unknown} ${SYS_WEB_SERVER_VERSION:-}"
            echo "Database:           ${SYS_DB_TYPE:-unknown} ${SYS_DB_VERSION:-}"
            echo "Firewall:           ${SYS_FIREWALL:-unknown} ${SYS_FIREWALL_VERSION:-} (${SYS_FIREWALL_ACTIVE:-unknown})"
            echo "PHP Versions:       ${SYS_PHP_VERSIONS[*]:-none detected}"
            echo ""
            echo "═══════════════════════════════════════════════════════════════"
            return 0
            ;;
        --clear-cache)
            # Initialize directories first
            init_directories || {
                echo "ERROR: Failed to initialize directories"
                return 1
            }

            # Clear all caches
            local cache_cleared=0

            # Production cache
            if [ -f "$BASE_DIR/.sysref" ] || [ -f "$BASE_DIR/.sysref.timestamp" ]; then
                rm -f "$BASE_DIR/.sysref" "$BASE_DIR/.sysref.timestamp" 2>/dev/null || true
                echo "✓ Cleared production cache (.sysref)"
                cache_cleared=1
            fi

            # Dev cache
            if [ -f "$BASE_DIR/.sysref.beta" ] || [ -f "$BASE_DIR/.sysref.beta.timestamp" ]; then
                rm -f "$BASE_DIR/.sysref.beta" "$BASE_DIR/.sysref.beta.timestamp" 2>/dev/null || true
                echo "✓ Cleared dev cache (.sysref.beta)"
                cache_cleared=1
            fi

            # Temp files
            if [ -d "$BASE_DIR/tmp" ]; then
                rm -rf "$BASE_DIR/tmp"/* 2>/dev/null || true
                echo "✓ Cleared temporary files"
                cache_cleared=1
            fi

            if [ $cache_cleared -eq 0 ]; then
                echo "ℹ️  No cache files to clear"
            else
                echo ""
                echo "Cache cleared successfully!"
                echo "System will auto-detect and rebuild cache on next run."
            fi
            return 0
            ;;
        --help|--usage|-h|-?)
            echo "Usage: launcher.sh [OPTIONS]"
            echo ""
            echo "Options:"
            echo "  --detect-only        Show system detection results and exit"
            echo "  --clear-cache        Clear all cache and temporary files"
            echo "  --help               Show this help message"
            echo ""
            echo "Examples:"
            echo "  bash launcher.sh --detect-only      # Check what was detected"
            echo "  bash launcher.sh --clear-cache      # Clear stale cache data"
            echo "  bash launcher.sh                    # Normal interactive mode"
            echo ""
            return 0
            ;;
    esac

    # Initialize directories once at startup
    init_directories || {
        echo "ERROR: Failed to initialize directories"
        return 1
    }

    # Detect system configuration (builds database if cache expired)
    startup_detection || true

    while true; do
        show_main_menu

        # Check if interactive mode
        if [ "$INTERACTIVE_MODE" -eq 0 ]; then
            echo ""
            echo "Non-interactive mode: Use this toolkit in an interactive terminal."
            echo "Try: source run.sh"
            return 0
        fi

        case "$MENU_CHOICE" in
            1) run_module "diagnostics" "system-health-check.sh" ;;
            2) handle_security_menu ;;
            3) handle_website_menu ;;
            4) handle_performance_menu ;;
            5) handle_backup_menu ;;
            6) handle_email_menu ;;
            7) run_module "maintenance" "cleanup-toolkit-data.sh" ;;
            0)
                echo ""
                echo "Clean history and remove traces? (yes/no): " >&2
                if ! read -r clean_hist </dev/tty 2>/dev/null; then
                    # Exit if read fails - just assume no cleanup
                    echo ""
                    echo "Thanks for using Server Management Toolkit!"
                    echo ""
                    return 0
                fi

                if [ "$clean_hist" = "yes" ]; then
                    touch /tmp/.cleanup_requested 2>/dev/null || true
                    echo ""
                    echo "Cleanup will happen automatically..."
                    echo ""
                else
                    echo ""
                    echo "Thanks for using Server Management Toolkit!"
                    echo ""
                fi
                return 0
                ;;
            *)
                menu_invalid_choice
                ;;
        esac
    done
}

main "$@"
