#!/bin/bash

# Network & Bandwidth Analyzer
# Analyzes bandwidth usage, network performance, and traffic patterns

# Get the script's directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TOOLKIT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"

# Source required libraries
source "$TOOLKIT_ROOT/lib/common-functions.sh"
source "$TOOLKIT_ROOT/lib/system-detect.sh"
source "$TOOLKIT_ROOT/lib/reference-db.sh"

# Initialize system detection
detect_system

# Load system info from reference database
if [ -f "$TOOLKIT_ROOT/.sysref" ]; then
    SYS_HOSTNAME=$(grep "^SYS|HOSTNAME|" "$TOOLKIT_ROOT/.sysref" 2>/dev/null | cut -d'|' -f3)
    SYS_PANEL=$(grep "^SYS|CONTROL_PANEL|" "$TOOLKIT_ROOT/.sysref" 2>/dev/null | cut -d'|' -f3)
    SYS_PANEL_VER=$(grep "^SYS|CONTROL_PANEL|" "$TOOLKIT_ROOT/.sysref" 2>/dev/null | cut -d'|' -f4)
    SYS_OS=$(grep "^SYS|OS|" "$TOOLKIT_ROOT/.sysref" 2>/dev/null | cut -d'|' -f3)
    SYS_OS_VER=$(grep "^SYS|OS|" "$TOOLKIT_ROOT/.sysref" 2>/dev/null | cut -d'|' -f4)
fi

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

# Report file
REPORT_FILE="/tmp/network_bandwidth_report_$(date +%Y%m%d_%H%M%S).txt"

# Analysis results storage
declare -a FINDINGS=()
declare -a RECOMMENDATIONS=()

# Function to add finding
add_finding() {
    [ -z "$1" ] || [ -z "$2" ] && return 1
    local severity="$1"
    local title="$2"
    local details="$3"
    local recommendation="$4"

    # Use @@@SEP@@@ as separator to avoid conflicts with content
    FINDINGS+=("[$severity] $title@@@SEP@@@$details@@@SEP@@@$recommendation")
}

# Function to check if command exists
command_exists() {
    [ -z "$1" ] && return 1
    command -v "$1" &>/dev/null
}

# Function to install vnstat if needed
check_and_offer_vnstat() {
    if ! command_exists vnstat; then
        echo -e "${YELLOW}[INFO]${NC} vnstat is not installed. vnstat provides historical bandwidth tracking."
        echo ""
        read -p "Would you like to install vnstat now? (y/n): " install_vnstat
        if [[ "$install_vnstat" =~ ^[Yy]$ ]]; then
            echo -e "${CYAN}[INFO]${NC} Installing vnstat..."
            if command_exists yum; then
                yum install -y vnstat
            elif command_exists apt-get; then
                apt-get update && apt-get install -y vnstat
            else
                echo -e "${RED}[ERROR]${NC} Could not determine package manager"
                return 1
            fi

            # Initialize vnstat database
            echo -e "${CYAN}[INFO]${NC} Initializing vnstat database..."
            systemctl enable vnstat --now 2>/dev/null || service vnstat start 2>/dev/null
            sleep 2
            echo -e "${GREEN}[OK]${NC} vnstat installed and started!"
            echo -e "${YELLOW}[NOTE]${NC} vnstat needs time to collect data. Initial stats will be limited."
            echo ""
        else
            echo -e "${YELLOW}[INFO]${NC} Skipping vnstat installation. Historical bandwidth data will not be available."
            return 1
        fi
    fi
    return 0
}

# Function to analyze bandwidth with vnstat
analyze_bandwidth_vnstat() {
    echo -e "${CYAN}[INFO]${NC} Analyzing historical bandwidth usage..."

    if ! check_and_offer_vnstat; then
        add_finding "INFO" "Historical Bandwidth Tracking Not Available" \
            "vnstat is not installed - cannot show historical bandwidth data" \
            "Install vnstat for bandwidth tracking: yum install vnstat"
        return
    fi

    # Get primary interface
    local interface=$(ip route | grep default | awk '{print $5}' | head -1)

    if [ -z "$interface" ]; then
        add_finding "WARNING" "Cannot Determine Network Interface" \
            "Unable to detect primary network interface" \
            "Check network configuration: ip route show"
        return
    fi

    # Check if vnstat has data for this interface
    if ! vnstat -i "$interface" &>/dev/null; then
        echo -e "${YELLOW}[INFO]${NC} Initializing vnstat for interface $interface..."
        vnstat --create -i "$interface" 2>/dev/null
        echo -e "${YELLOW}[NOTE]${NC} vnstat database created. Data collection will begin now."
        echo "         Run this tool again after some time to see bandwidth statistics."
        echo ""
        add_finding "INFO" "Bandwidth Monitoring Initialized" \
            "vnstat database created for interface $interface
Data collection started - statistics will be available after some usage" \
            "Run this analyzer again in 1+ hours to see bandwidth trends"
        return
    fi

    # Get monthly bandwidth
    local monthly_data=$(vnstat -i "$interface" -m --json 2>/dev/null)

    if [ -n "$monthly_data" ]; then
        # Extract current month data using basic parsing (fallback if jq not available)
        local current_month_rx=$(vnstat -i "$interface" -m | grep "$(date +%Y-%m)" | awk '{print $3, $4}' | head -1)
        local current_month_tx=$(vnstat -i "$interface" -m | grep "$(date +%Y-%m)" | awk '{print $6, $7}' | head -1)
        local current_month_total=$(vnstat -i "$interface" -m | grep "$(date +%Y-%m)" | awk '{print $9, $10}' | head -1)

        if [ -n "$current_month_total" ]; then
            add_finding "INFO" "Monthly Bandwidth Usage ($(date +%B))" \
                "Interface: $interface
Download: $current_month_rx
Upload:   $current_month_tx
Total:    $current_month_total" \
                "Monitor bandwidth trends daily to prevent overage"
        fi
    fi

    # Get daily bandwidth
    local daily_summary=$(vnstat -i "$interface" -d | tail -n 15 | head -n 10)
    if [ -n "$daily_summary" ]; then
        add_finding "INFO" "Daily Bandwidth Summary (Last 7 Days)" \
            "$daily_summary" \
            "Review daily patterns to identify unusual spikes"
    fi

    # Get hourly bandwidth for today
    local hourly_summary=$(vnstat -i "$interface" -h | tail -n 8)
    if [ -n "$hourly_summary" ]; then
        add_finding "INFO" "Hourly Bandwidth (Last 24 Hours)" \
            "$hourly_summary" \
            "Hourly view helps identify peak usage times"
    fi

    # Check for high bandwidth usage patterns
    local today_total=$(vnstat -i "$interface" -d | grep "$(date +%Y-%m-%d)" | awk '{print $9}')
    local today_value=$(echo "$today_total" | awk '{print $1}')
    local today_unit=$(echo "$today_total" | awk '{print $2}')

    if [ "$today_unit" = "GiB" ] && [ -n "$today_value" ]; then
        local high_usage=$(awk "BEGIN {print ($today_value > 50 ? 1 : 0)}" 2>/dev/null || echo 0)
        if [ "$high_usage" -eq 1 ]; then
            add_finding "WARNING" "High Daily Bandwidth Usage" \
                "Today's usage: $today_total
This is significantly higher than typical usage" \
                "Investigate traffic sources:
  • Check top bandwidth consumers (see analysis below)
  • Review Apache logs for unusual traffic
  • Check for backups or updates running
  • Look for bot/crawler traffic"
        fi
    fi
}

# Function to analyze Apache/web server traffic
analyze_web_traffic() {
    echo -e "${CYAN}[INFO]${NC} Analyzing web server traffic patterns..."

    # Multi-panel log directory discovery
    local log_dir=""
    if [ "$SYS_CONTROL_PANEL" = "interworx" ]; then
        # InterWorx: Multiple log locations (use first user's logs as sample)
        log_dir=$(find /home/*/var/*/logs -type d 2>/dev/null | head -1)
    elif [ "$SYS_CONTROL_PANEL" = "plesk" ]; then
        # Plesk: System logs
        log_dir="/var/www/vhosts/system"
    elif [ -n "$SYS_LOG_DIR" ] && [ -d "$SYS_LOG_DIR" ]; then
        # cPanel or detected log directory
        log_dir="$SYS_LOG_DIR"
    elif [ -d "/var/log/httpd" ]; then
        # Standalone fallback
        log_dir="/var/log/httpd"
    elif [ -d "/var/log/apache2" ]; then
        log_dir="/var/log/apache2"
    fi

    if [ -z "$log_dir" ] || [ ! -d "$log_dir" ]; then
        add_finding "INFO" "Web Server Logs Not Found" \
            "Could not locate Apache/web server logs (Panel: $SYS_CONTROL_PANEL)" \
            "Web traffic analysis requires Apache logs"
        return
    fi

    # Analyze top requesting IPs
    echo -e "${CYAN}[INFO]${NC} Finding top requesting IP addresses..."
    local top_ips=$(find "$log_dir" -name "*.log" -type f -mtime -1 -exec cat {} \; 2>/dev/null | \
        awk '{print $1}' | sort | uniq -c | sort -rn | head -10 | \
        awk '{printf "  • %8s requests - %s\n", $1, $2}')

    if [ -n "$top_ips" ]; then
        add_finding "INFO" "Top Requesting IPs (Last 24 Hours)" \
            "$top_ips" \
            "Investigate high-volume IPs:
  • Check if legitimate (search engines, monitoring)
  • Look for bot patterns in User-Agent
  • Consider rate limiting if abusive
  • Use Bot Analyzer for detailed analysis"
    fi

    # Analyze bandwidth by domain (if cPanel)
    if [ "$SYS_PANEL" = "cpanel" ]; then
        echo -e "${CYAN}[INFO]${NC} Analyzing per-domain bandwidth..."
        local domain_bandwidth=""

        for logfile in "$log_dir"/*.log; do
            [ -f "$logfile" ] || continue
            local domain=$(basename "$logfile" .log)
            local bytes=$(awk 'BEGIN {sum=0} {sum+=$10} END {print sum}' "$logfile" 2>/dev/null || echo "0")

            if [ "$bytes" -gt 0 ]; then
                local mb=$(awk "BEGIN {printf \"%.2f\", $bytes / 1048576}")
                domain_bandwidth+="  • $(printf '%-40s %10.2f MB' "$domain" "$mb")"$'\n'
            fi
        done

        if [ -n "$domain_bandwidth" ]; then
            domain_bandwidth=$(echo "$domain_bandwidth" | sort -k2 -rn | head -10)
            add_finding "INFO" "Top Bandwidth-Consuming Domains (Last 24 Hours)" \
                "$domain_bandwidth" \
                "Review high-bandwidth domains for:
  • Large file downloads
  • Media streaming
  • Bot/crawler traffic
  • Possible attacks or abuse"
        fi
    fi

    # Analyze top requested URLs/files
    echo -e "${CYAN}[INFO]${NC} Finding most requested URLs..."
    local top_urls=$(find "$log_dir" -name "*.log" -type f -mtime -1 -exec cat {} \; 2>/dev/null | \
        awk '{print $7}' | sort | uniq -c | sort -rn | head -10 | \
        awk '{printf "  • %8s requests - %s\n", $1, $2}')

    if [ -n "$top_urls" ]; then
        add_finding "INFO" "Most Requested URLs (Last 24 Hours)" \
            "$top_urls" \
            "Check for:
  • Broken links (404s)
  • Bot crawling patterns
  • Resource-intensive endpoints
  • Potential attack vectors"
    fi

    # Check for high bandwidth files
    echo -e "${CYAN}[INFO]${NC} Finding large bandwidth-consuming requests..."
    local large_transfers=$(find "$log_dir" -name "*.log" -type f -mtime -1 -exec cat {} \; 2>/dev/null | \
        awk '$10 > 10485760 {sum+=$10; count++} END {if (count > 0) printf "  • Total large files: %d\n  • Combined size: %.2f GB\n", count, sum/1073741824}')

    if [ -n "$large_transfers" ]; then
        add_finding "INFO" "Large File Transfers (>10MB each)" \
            "$large_transfers" \
            "Large file downloads can consume significant bandwidth
  • Consider CDN for large static files
  • Implement download throttling
  • Check for legitimate vs bot downloads"
    fi
}

# Function to analyze network connections
analyze_network_connections() {
    echo -e "${CYAN}[INFO]${NC} Analyzing network connections..."

    # Count connections by state
    local conn_states=$(netstat -an 2>/dev/null | awk '/^tcp/ {print $6}' | sort | uniq -c | sort -rn | \
        awk '{printf "  • %-20s %s\n", $2, $1}')

    if [ -n "$conn_states" ]; then
        add_finding "INFO" "TCP Connection States" \
            "$conn_states" \
            "Monitor connection states:
  • High TIME_WAIT: Normal after busy traffic
  • High CLOSE_WAIT: Possible application issues
  • High SYN_RECV: Possible SYN flood attack"
    fi

    # Count total connections
    local total_conn=$(netstat -an 2>/dev/null | grep -c "^tcp")
    if [ "$total_conn" -gt 1000 ]; then
        add_finding "WARNING" "High Number of TCP Connections" \
            "Current TCP connections: $total_conn
This may indicate high traffic or connection leak" \
            "Investigate connection sources:
  • netstat -an | grep ESTABLISHED | awk '{print \$5}' | cut -d: -f1 | sort | uniq -c | sort -rn
  • Check for connection pooling issues
  • Review application connection handling"
    fi

    # Top connecting IPs
    local top_conn_ips=$(netstat -an 2>/dev/null | grep ESTABLISHED | awk '{print $5}' | cut -d: -f1 | \
        sort | uniq -c | sort -rn | head -10 | awk '{printf "  • %8s connections - %s\n", $1, $2}')

    if [ -n "$top_conn_ips" ]; then
        add_finding "INFO" "Top Connected IP Addresses" \
            "$top_conn_ips" \
            "Review connection patterns from these IPs"
    fi
}

# Function to check network performance
analyze_network_performance() {
    echo -e "${CYAN}[INFO]${NC} Analyzing network performance..."

    # Get primary interface
    local interface=$(ip route | grep default | awk '{print $5}' | head -1)

    if [ -z "$interface" ]; then
        add_finding "WARNING" "Cannot Determine Network Interface" \
            "Unable to detect primary network interface" \
            "Check network configuration: ip route show"
        return
    fi

    # Get interface statistics
    local rx_errors=$(cat "/sys/class/net/$interface/statistics/rx_errors" 2>/dev/null || echo "0")
    local tx_errors=$(cat "/sys/class/net/$interface/statistics/tx_errors" 2>/dev/null || echo "0")
    local rx_dropped=$(cat "/sys/class/net/$interface/statistics/rx_dropped" 2>/dev/null || echo "0")
    local tx_dropped=$(cat "/sys/class/net/$interface/statistics/tx_dropped" 2>/dev/null || echo "0")

    if [ "$rx_errors" -gt 100 ] || [ "$tx_errors" -gt 100 ]; then
        add_finding "WARNING" "Network Interface Errors Detected" \
            "Interface: $interface
RX Errors: $rx_errors
TX Errors: $tx_errors
RX Dropped: $rx_dropped
TX Dropped: $tx_dropped" \
            "Network errors may indicate:
  • Hardware issues (cable, NIC)
  • Driver problems
  • Network congestion
Check: dmesg | grep -i $interface | tail -20"
    fi

    # Get MTU
    local mtu=$(ip link show "$interface" 2>/dev/null | grep mtu | awk '{print $5}')
    if [ -n "$mtu" ]; then
        if [ "$mtu" -ne 1500 ] && [ "$mtu" -ne 9000 ]; then
            add_finding "INFO" "Non-Standard MTU Detected" \
                "Interface: $interface
Current MTU: $mtu
Standard MTU is typically 1500 (or 9000 for jumbo frames)" \
                "Ensure MTU matches your network infrastructure
  • Test MTU: ping -M do -s 1472 8.8.8.8
  • Set MTU: ip link set $interface mtu 1500"
        else
            add_finding "INFO" "Network Interface Configuration" \
                "Interface: $interface
MTU: $mtu
RX Errors: $rx_errors
TX Errors: $tx_errors
RX Dropped: $rx_dropped
TX Dropped: $tx_dropped" \
                "Network interface appears healthy"
        fi
    fi

    # Check TCP statistics
    local tcp_retrans=$(netstat -s 2>/dev/null | grep "segments retransmitted" | awk '{print $1}' || echo "0")
    local tcp_out=$(netstat -s 2>/dev/null | grep "segments sent out" | awk '{print $1}' || echo "1")

    if [ "$tcp_out" -gt 1000000 ]; then
        local retrans_percent=$(awk "BEGIN {printf \"%.2f\", $tcp_retrans * 100 / $tcp_out}")
        local retrans_high=$(awk "BEGIN {print ($retrans_percent > 5 ? 1 : 0)}" 2>/dev/null || echo 0)

        if [ "$retrans_high" -eq 1 ]; then
            add_finding "WARNING" "High TCP Retransmission Rate" \
                "Retransmission rate: ${retrans_percent}%
Segments retransmitted: $tcp_retrans
Total segments sent: $tcp_out" \
                "High retransmission indicates network problems:
  • Test packet loss: ping -c 100 8.8.8.8
  • Check MTU settings
  • Review network congestion
  • Contact hosting provider if persistent"
        else
            add_finding "INFO" "TCP Retransmission Rate" \
                "Retransmission rate: ${retrans_percent}% (healthy)
Segments retransmitted: $tcp_retrans
Total segments sent: $tcp_out" \
                "TCP retransmission rate is within normal range"
        fi
    fi

    # Test connectivity to common DNS
    echo -e "${CYAN}[INFO]${NC} Testing network connectivity..."
    local ping_result=$(ping -c 5 -W 2 8.8.8.8 2>/dev/null | grep "packet loss" | awk '{print $6}' | tr -d '%')

    if [ -n "$ping_result" ]; then
        local packet_loss_high=$(awk "BEGIN {print ($ping_result > 5 ? 1 : 0)}" 2>/dev/null || echo 0)
        if [ "$packet_loss_high" -eq 1 ]; then
            add_finding "WARNING" "Packet Loss Detected" \
                "Packet loss to 8.8.8.8: ${ping_result}%
This indicates network connectivity issues" \
                "Investigate packet loss:
  • Test multiple targets: ping -c 100 [your-dns-server]
  • Check for network congestion
  • Review with hosting provider
  • Check interface errors (see above)"
        else
            local avg_latency=$(ping -c 5 -W 2 8.8.8.8 2>/dev/null | grep "avg" | awk -F'/' '{print $5}')
            add_finding "INFO" "Network Connectivity Test" \
                "Packet loss: ${ping_result}% (excellent)
Average latency: ${avg_latency}ms" \
                "Network connectivity is healthy"
        fi
    fi
}

# Function to recommend monitoring tools
recommend_monitoring_tools() {
    echo -e "${CYAN}[INFO]${NC} Checking for real-time monitoring tools..."

    local tools_needed=()
    local tools_installed=()

    # Check iftop
    if command_exists iftop; then
        tools_installed+=("iftop - Real-time bandwidth by connection")
    else
        tools_needed+=("iftop - Real-time bandwidth monitoring (yum install iftop)")
    fi

    # Check nethogs
    if command_exists nethogs; then
        tools_installed+=("nethogs - Bandwidth by process")
    else
        tools_needed+=("nethogs - Per-process bandwidth monitoring (yum install nethogs)")
    fi

    # Check nload
    if command_exists nload; then
        tools_installed+=("nload - Simple real-time traffic graph")
    else
        tools_needed+=("nload - Simple bandwidth monitor (yum install nload)")
    fi

    # Check iperf3
    if command_exists iperf3; then
        tools_installed+=("iperf3 - Network performance testing")
    else
        tools_needed+=("iperf3 - Bandwidth testing tool (yum install iperf3)")
    fi

    if [ ${#tools_installed[@]} -gt 0 ]; then
        local installed_list=$(printf '  • %s\n' "${tools_installed[@]}")
        add_finding "INFO" "Installed Monitoring Tools" \
            "$installed_list" \
            "Use these tools for real-time bandwidth monitoring"
    fi

    if [ ${#tools_needed[@]} -gt 0 ]; then
        local needed_list=$(printf '  • %s\n' "${tools_needed[@]}")
        add_finding "INFO" "Recommended Monitoring Tools" \
            "Consider installing these tools for better monitoring:
$needed_list" \
            "Install tools: yum install iftop nethogs nload iperf3
Usage examples:
  • iftop -i $interface  (real-time bandwidth by connection)
  • nethogs $interface   (bandwidth by process)
  • nload $interface     (simple traffic graph)
  • vnstat -l            (live traffic stats)"
    fi
}

# Function to generate report
generate_report() {
    local report_content=""

    report_content+="=============================================================================="$'\n'
    report_content+="NETWORK & BANDWIDTH ANALYSIS - $(date '+%Y-%m-%d %H:%M:%S')"$'\n'
    report_content+="=============================================================================="$'\n'
    report_content+=""$'\n'
    report_content+="System: $SYS_HOSTNAME"$'\n'
    report_content+="Control Panel: $SYS_PANEL ${SYS_PANEL_VER:-unknown}"$'\n'
    report_content+="OS: $SYS_OS ${SYS_OS_VER:-unknown}"$'\n'
    report_content+=""$'\n'

    # Group findings by category
    local -A categories
    categories["BANDWIDTH"]=""
    categories["WEB_TRAFFIC"]=""
    categories["CONNECTIONS"]=""
    categories["PERFORMANCE"]=""
    categories["TOOLS"]=""
    categories["OTHER"]=""

    for finding in "${FINDINGS[@]}"; do
        # Split by @@@SEP@@@ delimiter
        local severity_title="${finding%%@@@SEP@@@*}"
        local temp="${finding#*@@@SEP@@@}"
        local details="${temp%%@@@SEP@@@*}"
        local recommendation="${temp#*@@@SEP@@@}"

        # Extract severity from [SEVERITY] Title format
        local severity=$(echo "$severity_title" | sed -n 's/^\[\([^]]*\)\].*/\1/p')
        local title=$(echo "$severity_title" | sed 's/^\[[^]]*\] //')

        local category="OTHER"
        if [[ "$title" == *"Bandwidth"* ]] || [[ "$title" == *"Monthly"* ]] || [[ "$title" == *"Daily"* ]] || [[ "$title" == *"Hourly"* ]]; then
            category="BANDWIDTH"
        elif [[ "$title" == *"Domain"* ]] || [[ "$title" == *"URL"* ]] || [[ "$title" == *"Web"* ]] || [[ "$title" == *"IP"* ]]; then
            category="WEB_TRAFFIC"
        elif [[ "$title" == *"Connection"* ]]; then
            category="CONNECTIONS"
        elif [[ "$title" == *"Network"* ]] || [[ "$title" == *"TCP"* ]] || [[ "$title" == *"MTU"* ]] || [[ "$title" == *"Packet"* ]]; then
            category="PERFORMANCE"
        elif [[ "$title" == *"Tool"* ]] || [[ "$title" == *"Monitoring"* ]]; then
            category="TOOLS"
        fi

        local entry=""
        entry+="[$severity] $title"$'\n'
        entry+="$details"$'\n'
        if [ -n "$recommendation" ]; then
            entry+="Recommendation:"$'\n'
            entry+="$recommendation"$'\n'
        fi
        entry+=""$'\n'
        entry+="------------------------------------------------------------------------------"$'\n'
        entry+=""$'\n'

        categories[$category]+="$entry"
    done

    # Output sections
    if [ -n "${categories[BANDWIDTH]}" ]; then
        report_content+="=============================================================================="$'\n'
        report_content+="BANDWIDTH USAGE"$'\n'
        report_content+="=============================================================================="$'\n'
        report_content+=""$'\n'
        report_content+="${categories[BANDWIDTH]}"
    fi

    if [ -n "${categories[WEB_TRAFFIC]}" ]; then
        report_content+="=============================================================================="$'\n'
        report_content+="WEB TRAFFIC ANALYSIS"$'\n'
        report_content+="=============================================================================="$'\n'
        report_content+=""$'\n'
        report_content+="${categories[WEB_TRAFFIC]}"
    fi

    if [ -n "${categories[CONNECTIONS]}" ]; then
        report_content+="=============================================================================="$'\n'
        report_content+="NETWORK CONNECTIONS"$'\n'
        report_content+="=============================================================================="$'\n'
        report_content+=""$'\n'
        report_content+="${categories[CONNECTIONS]}"
    fi

    if [ -n "${categories[PERFORMANCE]}" ]; then
        report_content+="=============================================================================="$'\n'
        report_content+="NETWORK PERFORMANCE"$'\n'
        report_content+="=============================================================================="$'\n'
        report_content+=""$'\n'
        report_content+="${categories[PERFORMANCE]}"
    fi

    if [ -n "${categories[TOOLS]}" ]; then
        report_content+="=============================================================================="$'\n'
        report_content+="MONITORING TOOLS"$'\n'
        report_content+="=============================================================================="$'\n'
        report_content+=""$'\n'
        report_content+="${categories[TOOLS]}"
    fi

    if [ -n "${categories[OTHER]}" ]; then
        report_content+="=============================================================================="$'\n'
        report_content+="OTHER FINDINGS"$'\n'
        report_content+="=============================================================================="$'\n'
        report_content+=""$'\n'
        report_content+="${categories[OTHER]}"
    fi

    report_content+="=============================================================================="$'\n'
    report_content+="NEXT STEPS"$'\n'
    report_content+="=============================================================================="$'\n'
    report_content+=""$'\n'
    report_content+="Priority Actions:"$'\n'
    report_content+="  1. Review bandwidth usage trends for unusual patterns"$'\n'
    report_content+="  2. Investigate high-volume IP addresses and domains"$'\n'
    report_content+="  3. Address any network performance issues"$'\n'
    report_content+="  4. Consider installing monitoring tools for real-time tracking"$'\n'
    report_content+=""$'\n'
    report_content+="Additional Analysis Available:"$'\n'
    report_content+="  • Bot Analyzer (Main Menu → Security) for bot/attack traffic analysis"$'\n'
    report_content+="  • System Health Check (Main Menu) for overall server health"$'\n'
    report_content+=""$'\n'
    report_content+="Report saved to: $REPORT_FILE"$'\n'
    report_content+=""$'\n'

    echo "$report_content"
    echo "$report_content" > "$REPORT_FILE"
}

# Main execution
main() {
    show_banner
    echo -e "${BLUE}${BOLD}🌐 Network & Bandwidth Analyzer${NC}"
    echo ""
    echo ""

    echo -e "${CYAN}[INFO]${NC} Starting network and bandwidth analysis..."
    echo ""

    # Run analyses
    analyze_bandwidth_vnstat
    analyze_web_traffic
    analyze_network_connections
    analyze_network_performance
    recommend_monitoring_tools

    echo ""
    echo -e "${GREEN}[OK]${NC} Analysis complete!"
    echo ""

    # Generate and display report
    generate_report

    echo ""
    echo -e "${GREEN}[INFO]${NC} Full report saved to: ${CYAN}$REPORT_FILE${NC}"
    echo ""
    echo ""

    press_enter
}

# Run main function
main
