#!/bin/bash
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
source "$SCRIPT_DIR/lib/common-functions.sh"
source "$SCRIPT_DIR/lib/system-detect.sh"

print_banner "Web Traffic Monitor - Multi-Panel Support"
echo ""
echo "Monitoring Apache access logs in real-time..."
echo "Control Panel: ${SYS_CONTROL_PANEL}"
echo "Press Ctrl+C to exit"
echo ""

# Multi-panel log discovery
log_files=""
if [ "$SYS_CONTROL_PANEL" = "interworx" ]; then
    # InterWorx: Monitor recent access logs (uses 'transfer.log', limit for performance)
    log_files=$(find /home/*/var/*/logs -type f -name "transfer.log" -mmin -60 2>/dev/null | head -10)
elif [ "$SYS_CONTROL_PANEL" = "plesk" ]; then
    # Plesk: System logs
    log_files=$(find /var/www/vhosts/system/*/logs -type f -name "access_log" -o -name "access_ssl_log" 2>/dev/null | head -10)
elif [ -n "$SYS_LOG_DIR" ] && [ -d "$SYS_LOG_DIR" ]; then
    # cPanel: Use detected log directory
    log_files=$(find "$SYS_LOG_DIR" -type f ! -name "*-bytes_log" ! -name "*error_log" 2>/dev/null)
else
    # Standalone: Try common locations
    [ -f "/var/log/httpd/access_log" ] && log_files="/var/log/httpd/access_log"
    [ -f "/var/log/apache2/access.log" ] && log_files="$log_files /var/log/apache2/access.log"
fi

if [ -n "$log_files" ]; then
    tail -f $log_files 2>/dev/null | while read line; do
        ip=$(echo "$line" | awk '{print $1}')
        request=$(echo "$line" | awk '{print $6, $7}' | tr -d '"')
        status=$(echo "$line" | awk '{print $9}')

        # Color code by status
        if [[ "$status" =~ ^5 ]]; then
            color="\033[1;31m"  # Red for 5xx
        elif [[ "$status" =~ ^4 ]]; then
            color="\033[1;33m"  # Yellow for 4xx
        elif [[ "$status" =~ ^2 ]]; then
            color="\033[0;32m"  # Green for 2xx
        else
            color="\033[0;37m"  # White for others
        fi

        printf "${color}%-15s %s %s\033[0m\n" "$ip" "$status" "$request"
    done
else
    print_error "No Apache access logs found"
    echo "Control panel: $SYS_CONTROL_PANEL"
    echo "Log directory: $SYS_LOG_DIR"
    exit 1
fi
