#!/bin/bash
########################################
# Queue Worker Monitor & Auto-Restart
# For cPanel environments
# Run via cron every 5 minutes
########################################

# Configuration
PROJECT_ROOT="/home/globalgala/public_html/2026_backend_prod"
SCREEN_SESSION="showprima-queue"
LOG_FILE="$PROJECT_ROOT/storage/logs/queue-monitor.log"

# Change to project directory
cd "$PROJECT_ROOT" || exit 1

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

# Check if screen session exists and has a running process
check_worker_running() {
    # Check if screen session exists
    if ! screen -list | grep -q "$SCREEN_SESSION"; then
        return 1
    fi

    # Check if queue:work process is actually running
    if ! ps aux | grep "queue:work" | grep -v grep > /dev/null; then
        return 1
    fi

    return 0
}

# Start the queue worker
start_worker() {
    log "Starting queue worker..."

    # Kill any existing screen session (cleanup)
    screen -S "$SCREEN_SESSION" -X quit 2>/dev/null

    # Start new worker in screen session
    screen -dmS "$SCREEN_SESSION" bash -c "cd $PROJECT_ROOT && php artisan queue:work --queue=critical,emails,default,tickets,bulk --tries=3 --timeout=600 --sleep=3 --max-time=3600 --max-jobs=500 >> storage/logs/queue-worker.log 2>&1"

    # Wait a moment for worker to start
    sleep 2

    # Verify it started
    if check_worker_running; then
        log "✅ Queue worker started successfully"
        return 0
    else
        log "❌ Failed to start queue worker"
        return 1
    fi
}

# Main monitoring logic
main() {
    log "🔍 Checking queue worker status..."

    if check_worker_running; then
        log "✅ Queue worker is running"

        # Check pending jobs count
        pending_jobs=$(php artisan tinker --execute="echo \DB::table('jobs')->count();" 2>/dev/null | tail -1)
        log "📊 Pending jobs: $pending_jobs"

    else
        log "⚠️ Queue worker is NOT running - restarting..."
        start_worker

        # Send notification (optional - can integrate with email/slack later)
        log "📧 Queue worker was restarted - investigate why it stopped"
    fi
}

# Run the monitor
main

# Cleanup old log entries (keep last 1000 lines)
if [ -f "$LOG_FILE" ]; then
    tail -1000 "$LOG_FILE" > "$LOG_FILE.tmp" && mv "$LOG_FILE.tmp" "$LOG_FILE"
fi
