#!/bin/sh

# ─────────────────────────────────────────
# CONFIG
# ─────────────────────────────────────────
TARGETS="
/var/www/html/ACTIONS_MTF_MH
/var/www/html/ACTIONS_MH
"

LOG_DIR="/var/www/html/logs"
TIMESTAMP=$(date '+%Y%m%d_%H%M%S')
LOG_FILE="$LOG_DIR/cleanup_${TIMESTAMP}.log"
CURRENT_LINK="$LOG_DIR/cleanup_current.log"
MAX_LOG_FILES=3  # Number of log files to keep

# ─────────────────────────────────────────
# SETUP - Create directory
# ─────────────────────────────────────────
mkdir -p "$LOG_DIR"

# Remove old symlink if it exists and create new one pointing to current log
if [ -L "$CURRENT_LINK" ]; then
    rm -f "$CURRENT_LINK"
fi
ln -s "$LOG_FILE" "$CURRENT_LINK"

# Function to log with timestamp to both file and stdout (for systemd/journal)
log() {
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    local message="[$timestamp] $1"
    echo "$message" | tee -a "$LOG_FILE"
}

# Function to clean up old log files (keep only last MAX_LOG_FILES runs)
cleanup_old_logs() {
    log "--- CLEANING UP OLD LOG FILES ---"
    log "Maximum log files to keep: $MAX_LOG_FILES"
    
    # Count log files
    local log_files=$(ls -1 "$LOG_DIR"/cleanup_*.log 2>/dev/null | grep -v "cleanup_current.log" | wc -l)
    log "Total log files found: $log_files"
    
    # Keep only last MAX_LOG_FILES log files (delete oldest ones)
    if [ "$log_files" -gt "$MAX_LOG_FILES" ]; then
        local files_to_delete=$((log_files - MAX_LOG_FILES))
        log "Keeping only $MAX_LOG_FILES most recent log files. Removing $files_to_delete oldest file(s)..."
        
        # List files by modification time (oldest first) and delete excess
        ls -t "$LOG_DIR"/cleanup_*.log 2>/dev/null | grep -v "cleanup_current.log" | tail -n "$files_to_delete" | while IFS= read -r old_log; do
            if [ -f "$old_log" ] && [ ! -L "$old_log" ]; then
                log "  Removing old log file: $(basename "$old_log")"
                rm -f "$old_log"
            fi
        done
        
        # Verify cleanup
        local remaining_files=$(ls -1 "$LOG_DIR"/cleanup_*.log 2>/dev/null | grep -v "cleanup_current.log" | wc -l)
        log "Cleanup complete. $remaining_files log files remaining."
    else
        log "Log file count ($log_files) is within limit ($MAX_LOG_FILES). No files to delete."
    fi
}

# Function to capture and log directory listing with details
log_directory_contents() {
    local DIR="$1"
    local phase="$2"  # BEFORE or AFTER
    
    log "--- FILES $phase CLEANUP (detailed) ---"
    
    if [ ! -d "$DIR" ]; then
        log "Directory $DIR does not exist"
        return
    fi
    
    # Log directory info
    log "Directory info: $(ls -ld "$DIR" 2>&1)"
    
    # Capture full recursive listing with details
    log "Complete directory listing:"
    ls -laR "$DIR" 2>&1 | while IFS= read -r line; do
        if [ -n "$line" ]; then
            log "  $line"
        fi
    done
    
    # Also capture file count and total size
    if [ -d "$DIR" ]; then
        local file_count=$(find "$DIR" -type f 2>/dev/null | wc -l)
        local dir_count=$(find "$DIR" -type d 2>/dev/null | wc -l)
        local total_size=$(du -sh "$DIR" 2>/dev/null | cut -f1)
        log "  Summary: $file_count files, $dir_count directories, total size: $total_size"
    fi
}

# ─────────────────────────────────────────
# CLEANUP FUNCTION (deletes ALL files in directories)
# ─────────────────────────────────────────
cleanup_dir() {
    DIR="$1"

    log "========== PROCESSING: $DIR =========="
    log "ACTION: Deleting ALL files and subdirectories"

    # Check 1: Directory exists
    if [ ! -d "$DIR" ]; then
        log "ERROR: $DIR does not exist. Skipping."
        return
    fi

    # Log contents before deletion (detailed)
    log_directory_contents "$DIR" "BEFORE"

    # Check if directory is empty
    if [ -z "$(ls -A "$DIR" 2>/dev/null)" ]; then
        log "INFO: $DIR is already empty. Nothing to delete."
        return
    fi

    # Log what's about to be deleted
    log "Files and directories in $DIR to be deleted:"
    ls -la "$DIR" | grep -v "^total" | while IFS= read -r line; do
        if [ -n "$line" ]; then
            log "  $line"
        fi
    done

    # Critical safety check — cd into directory and verify
    cd "$DIR" || { log "ERROR: Failed to cd into $DIR. Aborting."; return; }

    if [ "$PWD" != "$DIR" ]; then
        log "ERROR: Directory mismatch! Expected $DIR but in $PWD. Aborting."
        return
    fi

    log "Current working directory verified: $PWD"

    # Perform cleanup - delete ALL contents
    log "Executing: rm -rf ./*"
    
    # Use find to delete with more verbose output
    local deleted_count=0
    find . -mindepth 1 -maxdepth 1 -exec echo "  Deleting: {}" \; -exec rm -rf {} \;
    EXIT_CODE=$?

    if [ $EXIT_CODE -eq 0 ]; then
        log "SUCCESS: Deleted all contents of $DIR (exit code: $EXIT_CODE)"
    else
        log "ERROR: rm failed in $DIR with exit code $EXIT_CODE"
    fi

    # Log contents after deletion (should be empty)
    log_directory_contents "$DIR" "AFTER"
    
    # Verify directory is empty
    if [ -z "$(ls -A "$DIR" 2>/dev/null)" ]; then
        log "VERIFICATION: $DIR is now empty"
    else
        log "WARNING: $DIR is not empty after deletion!"
        # Log what's left
        log "Remaining contents:"
        ls -la "$DIR" | while IFS= read -r line; do
            log "  $line"
        done
    fi
    
    log "========== DONE: $DIR =========="
    log ""
}

# ─────────────────────────────────────────
# MAIN
# ─────────────────────────────────────────
{
    echo "============================================"
    log "CLEANUP JOB STARTED"
    log "Log file: $LOG_FILE"
    log "Configuration:"
    log "  - Target directories: $(echo $TARGETS | tr '\n' ' ')"
    log "  - Action: Delete ALL files in target directories"
    log "  - Max log files to keep: $MAX_LOG_FILES"
    echo "============================================"

    # Log system info
    log "System: $(uname -a)"
    log "Hostname: $(hostname)"
    log "Current user: $(whoami)"
    
    # Check if directories exist before processing
    for DIR in $TARGETS; do
        if [ -d "$DIR" ]; then
            log "Target directory exists: $DIR"
        else
            log "WARNING: Target directory does not exist: $DIR"
        fi
    done

    # Process each target directory - delete ALL contents
    for DIR in $TARGETS; do
        cleanup_dir "$DIR"
    done

    # Clean up old log files (keep only last MAX_LOG_FILES runs)
    cleanup_old_logs


    #cleanup lock files
    rm /tmp/*.lock

    echo "============================================"
    log "CLEANUP JOB FINISHED"
    echo "============================================"
    log ""

} 2>&1 | tee -a "$LOG_FILE"

# Final output to console
echo ""
echo "✅ Done. All files deleted from target directories."
echo "   Log saved to: $LOG_FILE"
echo "   Current log symlink: $CURRENT_LINK -> $LOG_FILE"
echo "   Max log files kept: $MAX_LOG_FILES"