#!/usr/bin/env bash

# Setup SSH/FTP Log Monitoring Cron Job
# Simple version that just sets up the cron job during updates

set -euo pipefail

# Logging
LOG_FILE="/var/log/whp-setup.log"
SCRIPT_NAME="setup-ssh-ftp-monitoring"

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

# Main execution
main() {
    log_message "Starting SSH/FTP log monitoring setup"
    
    echo "Setting up SSH/FTP log monitoring system..."
    
    # Create necessary directories
    mkdir -p /var/log/proftpd
    mkdir -p /docker/whp/sql
    chmod 755 /var/log/proftpd
    chmod 755 /docker/whp/sql
    
    # Check if cron job already exists
    if crontab -l 2>/dev/null | grep -q "log_monitor_cron.sh"; then
        log_message "Cron job already exists, skipping setup"
        echo "Log monitoring cron job already configured"
    else
        # Add cron job to run every 5 minutes
        (crontab -l 2>/dev/null; echo "# WHP SSH/FTP Log Monitoring - Check logs every 5 minutes") | crontab -
        (crontab -l 2>/dev/null; echo "*/5 * * * * /root/whp/scripts/log_monitor_cron.sh >/dev/null 2>&1") | crontab -
        
        log_message "Cron job added successfully"
        echo "Log monitoring cron job configured to run every 5 minutes"
    fi
    
    echo ""
    echo "SSH/FTP Log Monitoring Setup Complete!"
    echo ""
    echo "The monitoring system will begin checking logs every 5 minutes."
    echo "Configure settings via the Security Management page in WHP."
    echo ""
    echo "Default configuration:"
    echo "  - SSH monitoring: Enabled"
    echo "  - FTP monitoring: Enabled"
    echo "  - Max attempts before block: 5"
    echo "  - Block duration: 1 hour"
    echo ""
    
    log_message "SSH/FTP log monitoring setup completed successfully"
}

# Execute main function
main "$@"