#!/usr/bin/env bash

# Log Monitor Cron Script
# This script runs every 5 minutes to check SSH and FTP logs for failed attempts
# and automatically blocks IPs that exceed the configured thresholds

set -euo pipefail

# Logging
LOG_FILE="/var/log/whp-log-monitor.log"
SCRIPT_NAME="log-monitor-cron"

# Function to log messages
log_message() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] [$SCRIPT_NAME] $1" >> "$LOG_FILE"
}

# Function to check if WHP web directory exists and is accessible
check_whp_directory() {
    if [[ ! -d "/docker/whp/web" ]]; then
        log_message "ERROR: WHP web directory not found at /docker/whp/web"
        exit 1
    fi
    
    if [[ ! -f "/docker/whp/web/libs/log_monitor_manager.php" ]]; then
        log_message "ERROR: Log monitor manager not found"
        exit 1
    fi
}

# Function to run log monitoring
run_log_monitor() {
    local php_script
    
    # Create temporary PHP script to run log monitoring with secure permissions
    php_script=$(mktemp -t log_monitor.XXXXXX)
    chmod 600 "$php_script"
    
    cat > "$php_script" << 'EOF'
<?php
// Change to the web directory so includes work correctly
chdir('/docker/whp/web');

// Include required libraries
require_once('/docker/whp/web/libs/log_monitor_manager.php');

try {
    $monitor = new log_monitor_manager();
    
    // Check logs for new failed attempts
    $monitor->check_logs();
    
    echo "Log monitoring completed successfully\n";
} catch (Exception $e) {
    echo "ERROR: " . $e->getMessage() . "\n";
    exit(1);
}
?>
EOF
    
    # Run the PHP script
    php "$php_script" 2>&1
    local exit_code=$?
    
    # Clean up temporary file
    rm -f "$php_script"
    
    return $exit_code
}

# Main execution
main() {
    log_message "Starting log monitoring check"
    
    # Check if WHP is properly installed
    check_whp_directory
    
    # Run log monitoring
    if run_log_monitor; then
        log_message "Log monitoring completed successfully"
    else
        log_message "ERROR: Log monitoring failed"
        exit 1
    fi
}

# Execute main function
main "$@"