#!/bin/bash
#############################################################################
# System Detection Diagnostic Tool
# Run this on a standalone server to test all detection functions
# Usage: bash test-detection.sh [verbose]
#############################################################################

set -eo pipefail

BASE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LIB_DIR="$BASE_DIR/lib"

# Check for verbose flag
VERBOSE=0
[ "$1" = "verbose" ] && VERBOSE=1

# Load libraries
source "$LIB_DIR/common-functions.sh"
source "$LIB_DIR/system-detect.sh"

echo "═══════════════════════════════════════════════════════════════"
echo "              SYSTEM DETECTION DIAGNOSTIC TOOL"
echo "═══════════════════════════════════════════════════════════════"
echo ""

#############################################################################
# STEP 1: Test Basic Commands
#############################################################################

echo "[STEP 1] Testing Command Availability"
echo "─────────────────────────────────────────────────────────────"

test_command() {
    local cmd="$1"
    local desc="$2"

    if command_exists "$cmd"; then
        local path=$(which "$cmd" 2>/dev/null)
        echo "✓ $desc"
        [ $VERBOSE -eq 1 ] && echo "  Location: $path"
    else
        echo "✗ $desc - NOT FOUND"
    fi
}

echo ""
echo "Web Servers:"
test_command "httpd" "Apache (httpd)"
test_command "apache2" "Apache (apache2)"
test_command "nginx" "Nginx"

echo ""
echo "Databases:"
test_command "mysql" "MySQL/MariaDB"
test_command "psql" "PostgreSQL"

echo ""
echo "Firewalls:"
test_command "firewall-cmd" "Firewalld"
test_command "iptables" "iptables"
test_command "ufw" "UFW"

#############################################################################
# STEP 2: Test Version Detection
#############################################################################

echo ""
echo "[STEP 2] Version Detection"
echo "─────────────────────────────────────────────────────────────"

echo ""
echo "Apache Version Detection:"
if command_exists httpd; then
    httpd_v=$(httpd -v 2>/dev/null | grep -oP 'Apache/\K[\d.]+' | head -1)
    echo "✓ httpd version: $httpd_v"
elif command_exists apache2; then
    apache2_v=$(apache2 -v 2>/dev/null | grep -oP 'Apache/\K[\d.]+' | head -1)
    echo "✓ apache2 version: $apache2_v"
else
    echo "✗ Apache not found"
fi

echo ""
echo "MySQL/MariaDB Version Detection:"
if command_exists mysql; then
    mysql_v=$(mysql --version 2>/dev/null)
    echo "✓ mysql version: $mysql_v"
else
    echo "✗ MySQL not found"
fi

echo ""
echo "Nginx Version Detection:"
if command_exists nginx; then
    nginx_v=$(nginx -v 2>&1 | grep -oP 'nginx/\K[\d.]+' 2>/dev/null)
    echo "✓ nginx version: $nginx_v"
else
    echo "✗ Nginx not found"
fi

#############################################################################
# STEP 3: Test Control Panel Detection
#############################################################################

echo ""
echo "[STEP 3] Control Panel Detection"
echo "─────────────────────────────────────────────────────────────"

echo ""
if [ -f "/usr/local/cpanel/version" ]; then
    cpanel_v=$(cat /usr/local/cpanel/version)
    echo "✓ cPanel detected: v$cpanel_v"
elif [ -f "/usr/local/psa/version" ]; then
    plesk_v=$(cat /usr/local/psa/version | head -1)
    echo "✓ Plesk detected: v$plesk_v"
elif [ -d "/usr/local/interworx" ] || [ -f "/etc/interworx/iworx.ini" ]; then
    echo "✓ InterWorx detected"
else
    echo "✓ Standalone (no control panel)"
fi

#############################################################################
# STEP 4: Test OS Detection
#############################################################################

echo ""
echo "[STEP 4] Operating System Detection"
echo "─────────────────────────────────────────────────────────────"

if [ -f /etc/os-release ]; then
    . /etc/os-release
    echo "✓ OS Detected: $NAME"
    echo "  Version: $VERSION_ID"
else
    echo "✗ Could not detect OS"
fi

#############################################################################
# STEP 5: Test Firewall Detection
#############################################################################

echo ""
echo "[STEP 5] Firewall Detection"
echo "─────────────────────────────────────────────────────────────"

echo ""
if [ -f "/etc/csf/csf.conf" ]; then
    csf_v=$(head -1 /etc/csf/version.txt 2>/dev/null || echo "unknown")
    echo "✓ CSF detected: v$csf_v"
    if pgrep -x lfd > /dev/null 2>&1; then
        echo "  Status: ACTIVE"
    else
        echo "  Status: INACTIVE"
    fi
else
    echo "✗ CSF not found"
fi

echo ""
if command_exists firewall-cmd; then
    fw_v=$(firewall-cmd --version 2>/dev/null || echo "unknown")
    echo "✓ firewalld detected: v$fw_v"
    if systemctl is-active --quiet firewalld 2>/dev/null; then
        echo "  Status: ACTIVE"
    else
        echo "  Status: INACTIVE"
    fi
else
    echo "✗ firewalld not found"
fi

echo ""
if command_exists iptables; then
    ipt_v=$(iptables --version 2>/dev/null | grep -oP 'v\K[\d.]+' | head -1 || echo "unknown")
    echo "✓ iptables detected: v$ipt_v"
    rules=$(iptables -L INPUT -n 2>/dev/null | wc -l)
    if [ "$rules" -gt 2 ]; then
        echo "  Status: ACTIVE ($(($rules - 2)) rules)"
    else
        echo "  Status: NO RULES"
    fi
else
    echo "✗ iptables not found"
fi

#############################################################################
# STEP 6: Run Full Detection
#############################################################################

echo ""
echo "[STEP 6] Running Full System Detection"
echo "─────────────────────────────────────────────────────────────"
echo ""

# Run the full detection
initialize_system_detection

#############################################################################
# STEP 7: Display Detected System Variables
#############################################################################

echo ""
echo "[STEP 7] Detected System Variables"
echo "─────────────────────────────────────────────────────────────"
echo ""

echo "Control Panel:     ${SYS_CONTROL_PANEL:-unknown}"
echo "Control Panel Ver: ${SYS_CONTROL_PANEL_VERSION:-N/A}"
echo "Operating System:  ${SYS_OS_TYPE:-unknown}"
echo "OS Version:        ${SYS_OS_VERSION:-N/A}"
echo "Web Server:        ${SYS_WEB_SERVER:-unknown}"
echo "Web Server Ver:    ${SYS_WEB_SERVER_VERSION:-N/A}"
echo "Database Type:     ${SYS_DB_TYPE:-unknown}"
echo "Database Ver:      ${SYS_DB_VERSION:-N/A}"
echo "Log Directory:     ${SYS_LOG_DIR:-N/A}"
echo "User Home Base:    ${SYS_USER_HOME_BASE:-N/A}"
echo "PHP Versions:      ${SYS_PHP_VERSIONS[*]:-N/A}"
echo "Firewall:          ${SYS_FIREWALL:-unknown}"
echo "Firewall Version:  ${SYS_FIREWALL_VERSION:-N/A}"
echo "Firewall Active:   ${SYS_FIREWALL_ACTIVE:-unknown}"
echo ""

#############################################################################
# STEP 8: Summary
#############################################################################

echo ""
echo "═══════════════════════════════════════════════════════════════"
echo "                         SUMMARY"
echo "═══════════════════════════════════════════════════════════════"
echo ""

detection_ok=1

[ -z "$SYS_WEB_SERVER" ] || [ "$SYS_WEB_SERVER" = "unknown" ] && {
    echo "⚠️  WARNING: Web server not detected"
    detection_ok=0
}

[ -z "$SYS_DB_TYPE" ] || [ "$SYS_DB_TYPE" = "none" ] && {
    echo "⚠️  INFO: No database detected (may be intentional)"
}

[ -z "$SYS_FIREWALL" ] || [ "$SYS_FIREWALL" = "none" ] && {
    echo "ℹ️  INFO: No firewall detected (may be intentional on standalone)"
}

if [ $detection_ok -eq 1 ]; then
    echo "✓ System detection completed successfully"
    echo ""
    echo "All critical components detected."
fi

echo ""
echo "═══════════════════════════════════════════════════════════════"
echo ""
