#!/bin/bash

# Configuration
DISPATCH_DIR="/home/dodom2/public_html/ftp.stationboss.net/dispatch"
PHP_SCRIPT="/home/dodom2/public_html/ftp.stationboss.net/ftp_process_upload.php" 
LOG_DIR="/home/dodom2/public_html/ftp.stationboss.net/logs"

# Function to get current log file path
get_log_file() {
    echo "$LOG_DIR/$(date '+%Y/%m')/dispatch-monitor-$(date '+%Y-%m-%d').log"
}

# Function to log messages with timestamp
log_message() {
    local LOG_FILE=$(get_log_file)
    mkdir -p "$(dirname "$LOG_FILE")"
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> "$LOG_FILE"
}

# Check if directories exist
if [ ! -d "$DISPATCH_DIR" ]; then
    log_message "ERROR: Dispatch directory $DISPATCH_DIR does not exist!"
    exit 1
fi

if [ ! -f "$PHP_SCRIPT" ]; then
    log_message "ERROR: PHP script $PHP_SCRIPT does not exist!"
    exit 1
fi

log_message "Starting dispatch folder monitoring..."

# Monitor for file close_write(FTP), moved_to(HTTP) events in all subdirectories of dispatch
inotifywait -m -r -e close_write,moved_to --format '%w%f' "$DISPATCH_DIR" | while read FILE_PATH
do
    # Check if the detected path is a file (not a directory)
    if [ -f "$FILE_PATH" ]; then
        # Skip files in archive folders to prevent infinite processing loop
        if [[ "$FILE_PATH" == */archive/* ]]; then
            log_message "Skipping archived file: $FILE_PATH"
            continue
        fi
        
        # Get the filename from the full path
        FILENAME=$(basename "$FILE_PATH")
        
        # Skip hidden files (starting with .) - includes .ftpquota and other system files
        if [[ "$FILENAME" == .* ]]; then
            log_message "Skipping hidden/system file: $FILE_PATH"
            continue
        fi
        
        log_message "New file detected: $FILE_PATH"
        
        # Get current log file for output redirection
        CURRENT_LOG=$(get_log_file)
        mkdir -p "$(dirname "$CURRENT_LOG")"
        
        # Call the PHP script with the file path as an argument
        /opt/cpanel/ea-php82/root/usr/bin/php "$PHP_SCRIPT" "$FILE_PATH" >> "$CURRENT_LOG" 2>&1
        
        # Check if PHP script executed successfully
        if [ $? -eq 0 ]; then
            log_message "Successfully processed: $FILE_PATH"
        else
            log_message "ERROR: Failed to process: $FILE_PATH"
        fi
    fi
done
