<?php
declare(strict_types=1);
// Inherit secrets in memory from a verified existing isolated worker, never argv/log.
$lane = $argv[1] ?? '';
if (!in_array($lane, ['B', 'C'], true)) exit(78);
$pid = $lane === 'B' ? 10001 : 112175;
$root = $lane === 'B' ? '/tmp/zhct-http-store-mysql.dQTTBP' : '/tmp/zhct-dm-poc-20260928.fcpiiN/store';
$oldPort = $lane === 'B' ? 18081 : 18080;
$port = $lane === 'B' ? 18082 : 18083;
$cmdline = (string)file_get_contents('/proc/' . $pid . '/cmdline');
if (strpos($cmdline, $root . '/public') === false || strpos($cmdline, '127.0.0.1:' . $oldPort) === false) {
    throw new RuntimeException('Original worker drift');
}
if ($socket = @fsockopen('127.0.0.1', $port, $errno, $error, 1)) {
    fclose($socket); throw new RuntimeException('Pilot port occupied');
}
$env = [];
foreach (explode("\0", (string)file_get_contents('/proc/' . $pid . '/environ')) as $entry) {
    $pair = explode('=', $entry, 2);
    if (count($pair) === 2) $env[$pair[0]] = $pair[1];
}
if (($env['POC_EXTERNAL_STUBS'] ?? '') !== '1' || ($env['POC_REAL_QUEUE'] ?? '0') !== '0') {
    throw new RuntimeException('Original worker unsafe');
}
if ($lane === 'C' && (($env['POC_HOST'] ?? '') !== '127.0.0.1'
    || ($env['POC_PORT'] ?? '') !== '5237' || ($env['POC_SCHEMA'] ?? '') !== 'ZHCT_APP')) {
    throw new RuntimeException('DM identity drift');
}
$env['PILOT_LANE'] = $lane;
$env['PILOT_TARGET_ROOT'] = $root;
$php = $lane === 'B' ? '/usr/local/php7.3/bin/php' : '/www/server/php/73/bin/php';
$args = [$php];
if ($lane === 'C') {
    array_push($args, '-c', '/www/server/php/73/etc/php-cli.ini',
        '-d', 'extension=/home/dmdba/dmdbms/drivers/php_pdo/libphp73_dm.so',
        '-d', 'extension=/home/dmdba/dmdbms/drivers/php_pdo/php73_pdo_dm.so');
}
array_push($args, '-d', 'display_errors=0', '-d', 'log_errors=0', '-S', '127.0.0.1:' . $port,
    '-t', __DIR__, __DIR__ . '/index.php');
$command = 'nohup ' . implode(' ', array_map('escapeshellarg', $args)) . ' </dev/null >/dev/null 2>&1 & echo $!';
$process = proc_open($command, [1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes, null, $env);
$out = stream_get_contents($pipes[1]); $err = stream_get_contents($pipes[2]);
fclose($pipes[1]); fclose($pipes[2]); $exit = proc_close($process);
if ($exit !== 0 || !ctype_digit(trim($out)) || $err !== '') throw new RuntimeException('Pilot startup failed');
echo json_encode(['lane' => $lane, 'pid' => (int)trim($out), 'port' => $port]), "\n";
