#!/bin/bash
# Persistent queue worker with automatic restart and daily log rotation.
# Run once as a background process: nohup bash queue-worker.sh &
#
# --max-jobs=50  : exit cleanly after 50 jobs (prevents memory creep)
# --memory=96    : exit cleanly if RSS exceeds 96MB (below PHP's 128MB limit)
# --timeout=60   : kill a stuck job after 60s

cd "$(dirname "$0")"

log() {
    local file="storage/logs/queue-worker-$(date -u +"%Y-%m-%d").log"
    echo "[$(date -u +"%Y-%m-%d %H:%M:%S UTC")] $1" >> "$file"
}

while true; do
    log "Worker starting"
    php artisan queue:work database \
        --max-jobs=50 \
        --memory=96 \
        --timeout=60 \
        --sleep=3 \
        --tries=5 \
        >> "storage/logs/queue-worker-$(date -u +"%Y-%m-%d").log" 2>&1
    log "Worker exited (code $?), restarting in 2s..."
    sleep 2
done
