<?php
declare(strict_types=1);

$mode = (string)($argv[1] ?? '');
if (!in_array($mode, ['--preflight', '--execute'], true)
    || ($mode === '--execute' && (string)getenv('CDX_SPICY_APPROVED') !== 'ROOT_WINDOW_APPROVED')) {
    echo json_encode(['status' => 'default_deny']), PHP_EOL;
    exit(78);
}
$pid = 112175;
$cmd = (string)@file_get_contents('/proc/' . $pid . '/cmdline');
if (strpos($cmd, '/tmp/zhct-dm-poc-20260928.fcpiiN/store/public') === false
    || strpos($cmd, '127.0.0.1:18080') === false) {
    throw new RuntimeException('C isolated worker changed');
}
$environment = [];
foreach (explode("\0", (string)@file_get_contents('/proc/' . $pid . '/environ')) as $entry) {
    $at = strpos($entry, '=');
    if ($at !== false) $environment[substr($entry, 0, $at)] = substr($entry, $at + 1);
}
$servicePath = (string)($environment['DM_SVC_PATH'] ?? '');
if (($environment['POC_PORT'] ?? '') !== '5237'
    || ($environment['POC_SCHEMA'] ?? '') !== 'ZHCT_APP'
    || substr(hash('sha256', $servicePath), 0, 12) !== '5a92d26aec07'
    || !is_file($servicePath . '/dm_svc.conf')
    || strpos((string)file_get_contents($servicePath . '/dm_svc.conf'),
        'CHAR_CODE=(PG_UTF8)') === false) {
    throw new RuntimeException('C DM client boundary changed');
}
$dir = __DIR__;
$runner = $dir . '/runner.php';
$runnerSha = 'e5c920b376b8c5146bf6ec66f27a97555cf7f70c94a4797a78c9c2bd2512b89a';
if (is_link($dir) || is_link($runner) || !is_file($runner)
    || (fileperms($dir) & 0777) !== 0700
    || (fileperms($runner) & 0777) !== 0600
    || hash_file('sha256', $runner) !== $runnerSha) {
    throw new RuntimeException('C private runner changed');
}
$environment['CDX_SPICY_LANE'] = 'C';
if ($mode === '--execute') {
    $environment['CDX_SPICY_EXECUTE'] = 'ROOT_WINDOW_APPROVED';
    $environment['CDX_SPICY_SHA'] = $runnerSha;
}
$command = escapeshellarg('/www/server/php/73/bin/php')
    . ' -d display_errors=0 -d log_errors=0'
    . ' -d extension=/home/dmdba/dmdbms/drivers/php_pdo/php73_pdo_dm.so'
    . ' ' . escapeshellarg($runner) . ' ' . escapeshellarg($mode);
$process = proc_open($command, [1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes, null, $environment);
if (!is_resource($process)) throw new RuntimeException('C PHP process unavailable');
$stdout = stream_get_contents($pipes[1]);
$stderr = stream_get_contents($pipes[2]);
fclose($pipes[1]);
fclose($pipes[2]);
$exitCode = proc_close($process);
$decoded = json_decode((string)$stdout, true);
if (!is_array($decoded)) {
    echo json_encode(['status' => 'redacted_child_error', 'exit' => $exitCode,
        'stderr' => $stderr === '' ? 'empty' : 'nonempty']), PHP_EOL;
    exit($exitCode === 0 ? 2 : $exitCode);
}
echo json_encode(['exit' => $exitCode, 'result' => $decoded,
    'stderr' => $stderr === '' ? 'empty' : 'nonempty'], JSON_UNESCAPED_SLASHES), PHP_EOL;
exit($exitCode);
