#!/bin/bash
# Worker management script to prevent process accumulation

# Determine PHP path
PHP_BIN="/usr/local/bin/php"
if [ ! -f "$PHP_BIN" ]; then
    PHP_BIN="/usr/bin/php"
fi

# Determine base directory path
BASE_DIR="/var/www/html"
if [ ! -d "$BASE_DIR" ]; then
    BASE_DIR="/var/www/html"
fi

echo "[$(date)] --- Worker Management Start ---"

# Kill existing workers using full path and bracket trick to avoid killing itself
echo "[$(date)] Terminating existing workers..."
/usr/bin/pkill -f "[p]ending-order-executed.php" || true
/usr/bin/pkill -f "[c]heck_pending_order_execute.php" || true

# Wait 2 seconds for clean release of resources and sockets
sleep 2

# Start the pending-order-executed.php worker in the background
echo "[$(date)] Launching pending-order-executed.php worker..."
$PHP_BIN $BASE_DIR/public/admin/cron/pending-order-executed.php > $BASE_DIR/public/logdata/pending-order-executed.log 2>&1 &

# Start the check_pending_order_execute.php worker in the background
echo "[$(date)] Launching check_pending_order_execute.php worker..."
$PHP_BIN $BASE_DIR/public/admin/cron/check_pending_order_execute.php >> $BASE_DIR/public/logdata/check_pending_order_execute.log 2>&1 &

echo "[$(date)] --- Worker Management Complete ---"
