#!/bin/bash
# run-queue-worker.sh — Cron-safe queue worker launcher
# 
# Cek apakah queue worker sudah jalan. Kalau belum, jalankan.
# Pasang di cron setiap 1 menit:
#   * * * * * /home/rasamemek/public_html/player2027/run-queue-worker.sh >> /dev/null 2>&1
#

SITE_DIR="/home/rasamemek/public_html/player2027"
PHP_BIN="/opt/cpanel/ea-php82/root/usr/bin/php"
PHP_FALLBACKS=("/usr/bin/php" "$(which php 2>/dev/null)")
LOG_FILE="$SITE_DIR/storage/logs/queue-worker.log"
LOCK_FILE="$SITE_DIR/storage/framework/queue-worker.lock"

# Check if PHP binary exists and is CLI (avoid php-cgi). Try known CLI locations then fallbacks.
is_cgi() {
    local p="$1"
    [ -x "$p" ] || return 1
    local name
    name=$(basename "$p")
    case "$name" in
        php-cgi|php-cgi.*|php-fpm*) return 0 ;;
        *) return 1 ;;
    esac
}

if [ ! -x "$PHP_BIN" ] || is_cgi "$PHP_BIN"; then
    for alt in "${PHP_FALLBACKS[@]}"; do
        if [ -n "$alt" ] && [ -x "$alt" ] && ! is_cgi "$alt"; then
            PHP_BIN="$alt"
            break
        fi
    done
fi

# If still not found, try which php but avoid cgi
if [ ! -x "$PHP_BIN" ] || is_cgi "$PHP_BIN"; then
    W=$(which php 2>/dev/null || true)
    if [ -n "$W" ] && [ -x "$W" ] && ! is_cgi "$W"; then
        PHP_BIN="$W"
    fi
fi

# Check if a worker is already running
if [ -f "$LOCK_FILE" ]; then
    PID=$(cat "$LOCK_FILE")
    if kill -0 "$PID" 2>/dev/null; then
        # Worker is still alive, do nothing
        exit 0
    else
        # Stale lock file, remove it
        rm -f "$LOCK_FILE"
    fi
fi

# Check if there are pending jobs
PENDING=$($PHP_BIN "$SITE_DIR/artisan" tinker --execute="echo \Illuminate\Support\Facades\DB::table('jobs')->where('queue','video-encode')->count();" 2>/dev/null | tail -1)

if [ "$PENDING" = "0" ] || [ -z "$PENDING" ]; then
    # No pending jobs, don't start worker
    exit 0
fi

# Start worker in background
cd "$SITE_DIR"
nohup $PHP_BIN -d max_execution_time=0 artisan queue:work --queue=video-encode --timeout=7200 --tries=10 --sleep=5 --max-jobs=100 >> "$LOG_FILE" 2>&1 &
WORKER_PID=$!

# Save PID to lock file
echo "$WORKER_PID" > "$LOCK_FILE"

echo "[$(date)] Queue worker started (PID: $WORKER_PID, pending: $PENDING)" >> "$LOG_FILE"
