<?php
function isProcessRunning($pid) {
    if (!$pid) return false;
    return posix_kill((int)$pid, 0);
}

$runnerFile = __DIR__ . "/runner.json";

if (!file_exists($runnerFile)) {
    die("runner.json not found\n");
}

$data = json_decode(file_get_contents($runnerFile), true);

if (!$data || !isset($data['command'])) {
    die("Invalid runner.json\n");
}

$command = $data['command'];
$pid     = $data['pid'] ?? null;

/**
 * Check if PID is running
 */

if ($pid && isProcessRunning($pid)) {
    echo "✅ Process already running | PID: $pid\n";
    exit;
}

echo "❌ Process not running. Restarting...\n";

/**
 * Run command in background & get new PID
 */
exec($command . " > /dev/null 2>&1 & echo $!", $output);
$newPid = isset($output[0]) ? (int)$output[0] : null;

if (!$newPid) {
    die("Failed to start process\n");
}
