<?php
declare(strict_types=1);

// Private PHP built-in-server router template. Never launch against a live site.
// It holds ONLY this run's activate request until both new workers arrive.
$root = (string)getenv('CDX_EM_RACE_PRIVATE_ROOT');
$barrierDir = (string)getenv('CDX_EM_RACE_BARRIER_DIR');
$side = (int)getenv('CDX_EM_RACE_SIDE');
$routerSha = (string)getenv('CDX_EM_RACE_ROUTER_SHA');
if (!preg_match('~^/tmp/cdx-em-race-[abc]-[a-f0-9]{12}-[12]$~D', $root)
    || !preg_match('~^/tmp/cdx-em-race-barrier-[a-f0-9]{12}$~D', $barrierDir)
    || !in_array($side, [1, 2], true)
    || realpath($root) !== $root || realpath($barrierDir) !== $barrierDir
    || is_link($root) || is_link($barrierDir)
    || (((int)fileperms($root) & 0077) !== 0)
    || (((int)fileperms($barrierDir) & 0077) !== 0)
    || !hash_equals((string)hash_file('sha256', __FILE__), $routerSha)) {
    http_response_code(503);
    echo 'isolated-router-disabled';
    return;
}
$guardPath = $barrierDir . '/guard.json';
$statePath = $barrierDir . '/state.json';
if (is_link($guardPath) || is_link($statePath)
    || !is_file($guardPath) || !is_file($statePath)
    || (((int)fileperms($guardPath) & 0077) !== 0)
    || (((int)fileperms($statePath) & 0077) !== 0)) {
    http_response_code(503);
    echo 'isolated-guard-absent';
    return;
}
$guard = json_decode((string)file_get_contents($guardPath), true);
if (!is_array($guard) || ($guard['status'] ?? null) !== 'prepared'
    || !preg_match('/^CDXEMRACE[A-F0-9]{12}$/D',
        (string)($guard['marker'] ?? ''))
    || !isset($guard['device_ids'][1], $guard['device_ids'][2])
    || ($guard['device_ids'][1] ?? '') === ($guard['device_ids'][2] ?? '')) {
    http_response_code(503);
    echo 'isolated-guard-invalid';
    return;
}
$readState = static function () use ($statePath): array {
    $handle = fopen($statePath, 'rb');
    if ($handle === false || !flock($handle, LOCK_SH)) {
        throw new RuntimeException('Private race state read lock unavailable');
    }
    try {
        $state = json_decode((string)stream_get_contents($handle), true);
        if (!is_array($state)) throw new RuntimeException('Private race state invalid');
        return $state;
    } finally {
        flock($handle, LOCK_UN);
        fclose($handle);
    }
};
$path = parse_url((string)($_SERVER['REQUEST_URI'] ?? ''), PHP_URL_PATH);
if ($path === '/__poc_boundary') {
    require $root . '/public/router.php';
    return;
}
if ($path === '/__poc_race_status') {
    $state = $readState();
    header('Content-Type: application/json');
    echo json_encode(['private_race_router' => true, 'pid' => getmypid(),
        'side' => $side, 'source_sha_match' => true,
        'arrived_count' => is_array($state)
            ? count(array_filter($state['arrivals'] ?? [])) : -1,
        'released' => is_array($state) && ($state['released'] ?? false) === true,
        'aborted' => is_array($state) && ($state['aborted'] ?? false) === true]);
    return;
}
if ($path !== '/api/electronicMenu/device/activate'
    || ($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST'
    || (string)($_POST['device_id'] ?? '') !== (string)$guard['device_ids'][$side]) {
    http_response_code(404);
    echo 'private-route-not-allowed';
    return;
}
$updateState = static function (callable $mutate) use ($statePath): array {
    $handle = fopen($statePath, 'c+');
    if ($handle === false || !flock($handle, LOCK_EX)) {
        throw new RuntimeException('Private race state lock unavailable');
    }
    try {
        rewind($handle);
        $state = json_decode((string)stream_get_contents($handle), true);
        if (!is_array($state) || !is_array($state['arrivals'] ?? null)
            || !array_key_exists(1, $state['arrivals'])
            || !array_key_exists(2, $state['arrivals'])) {
            throw new RuntimeException('Private race state invalid');
        }
        $state = $mutate($state);
        $json = json_encode($state, JSON_UNESCAPED_SLASHES);
        if (!is_string($json) || ftruncate($handle, 0) === false
            || !rewind($handle)
            || fwrite($handle, $json) !== strlen($json)
            || !fflush($handle)) {
            throw new RuntimeException('Private race state write failed');
        }
        return $state;
    } finally {
        flock($handle, LOCK_UN);
        fclose($handle);
    }
};
try {
    $now = microtime(true);
    $state = $updateState(static function (array $state) use ($side, $now): array {
        if (($state['aborted'] ?? false) === true
            || ($state['released'] ?? false) === true
            || !empty($state['arrivals'][$side])) {
            throw new RuntimeException('Private race replay/abort');
        }
        $state['arrivals'][$side] = ['pid' => getmypid(), 'time' => $now];
        if (!empty($state['arrivals'][1]) && !empty($state['arrivals'][2])) {
            $state['released'] = true;
            $state['released_at'] = microtime(true);
        }
        return $state;
    });
    $deadline = microtime(true) + 5.0;
    while (($state['released'] ?? false) !== true) {
        if (microtime(true) >= $deadline) {
            $state = $updateState(static function (array $current): array {
                if (($current['released'] ?? false) !== true) {
                    $current['aborted'] = true;
                    $current['aborted_at'] = microtime(true);
                }
                return $current;
            });
            break;
        }
        usleep(20000);
        $state = $readState();
        if (($state['aborted'] ?? false) === true) break;
    }
    if (!is_array($state) || ($state['released'] ?? false) !== true
        || ($state['aborted'] ?? false) === true) {
        http_response_code(503);
        echo 'private-race-rendezvous-aborted';
        return;
    }
    $updateState(static function (array $state) use ($side): array {
        $state['dispatch'][$side] = microtime(true);
        return $state;
    });
    require $root . '/public/router.php';
} catch (Throwable $error) {
    http_response_code(503);
    echo 'private-race-rendezvous-failed';
}
