#!/usr/bin/env bash
# ==============================================================================
# ZegaCloud Worker Watchdog for cPanel / CloudLinux Node.js Selector
# ==============================================================================
# Usage in cPanel Cron:
# */5 * * * * /home/YOUR_USER/scripts/cpanel-worker-cron.sh >> /home/YOUR_USER/worker_cron.log 2>&1
# ==============================================================================

set -e

APP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
LOCK_FILE="/tmp/zega_worker_cron.lock"
PORT="${PORT:-3051}"
HEALTH_URL="http://127.0.0.1:${PORT}/health"

# Prevent concurrent watchdog runs
exec 200>"$LOCK_FILE"
flock -n 200 || exit 0

echo "[$(date -u +"%Y-%m-%dT%H:%M:%SZ")] Checking ZegaCloud background worker status on port ${PORT}..."

# Check if worker is responding to health endpoint
HTTP_STATUS=$(curl -s -o /dev/null -w "%{http_code}" --max-time 5 "$HEALTH_URL" || echo "000")

if [ "$HTTP_STATUS" = "200" ]; then
    echo "[OK] Worker is healthy and responsive (HTTP $HTTP_STATUS)."
    exit 0
else
    echo "[WARN] Worker health check failed or unresponsive (HTTP $HTTP_STATUS). Initiating restart..."
    
    # Check if a stale node process is stuck
    STALE_PID=$(pgrep -f "apps/worker/dist/index.js" || true)
    if [ -n "$STALE_PID" ]; then
        echo "[INFO] Terminating stale worker PID: $STALE_PID"
        kill -15 "$STALE_PID" 2>/dev/null || true
        sleep 2
        kill -9 "$STALE_PID" 2>/dev/null || true
    fi

    # Start worker process in background
    cd "$APP_DIR"
    nohup node apps/worker/dist/index.js >> "$APP_DIR/storage/worker_runtime.log" 2>&1 &
    NEW_PID=$!
    echo "[RESTARTED] Worker launched with PID $NEW_PID."
fi
