<?php
declare(strict_types=1);

// One bounded SELECT-only C probe under the already isolated Store worker env.
if (count($argv) !== 2 || ($argv[1] ?? '') !== '--probe'
    || (string)getenv('CDX_SQLFUNC_C_RELEASE') !== 'ROOT_FIXED_CONSTANT_SELECT_ONLY_V1') {
    echo json_encode(['status' => 'default_deny', 'http_sent' => false,
        'dml' => false]), PHP_EOL;
    exit(78);
}
$pid = 112175;
$cmdline = (string)@file_get_contents('/proc/' . $pid . '/cmdline');
if (strpos($cmdline, '/tmp/zhct-dm-poc-20260928.fcpiiN/store/public') === false
    || strpos($cmdline, '127.0.0.1:18080') === false) {
    throw new RuntimeException('C isolated worker drift');
}
$env = [];
foreach (explode("\0", (string)@file_get_contents('/proc/' . $pid . '/environ')) as $entry) {
    $at = strpos($entry, '=');
    if ($at !== false) $env[substr($entry, 0, $at)] = substr($entry, $at + 1);
}
$servicePath = (string)($env['DM_SVC_PATH'] ?? '');
if (($env['POC_PORT'] ?? '') !== '5237'
    || ($env['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 drift');
}
$directory = __DIR__;
$runner = $directory . '/runner.php';
$expected = 'f041e93e5cb0ee57ea43a51a1b08631b87cd84601d1e5517f035ff58291f8a87';
if (is_link($directory) || is_link($runner) || !is_file($runner)
    || (fileperms($directory) & 0777) !== 0700
    || (fileperms($runner) & 0777) !== 0600
    || hash_file('sha256', $runner) !== $expected) {
    throw new RuntimeException('C private runner boundary drift');
}
$env['CDX_SQLFUNC_LANE'] = 'C';
$env['CDX_SQLFUNC_APPROVE'] = 'FIXED_CONSTANT_SELECT_ONLY_V1';
$env['CDX_SQLFUNC_SHA'] = $expected;
$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) . ' --probe';
$process = proc_open($command, [1 => ['pipe', 'w'], 2 => ['pipe', 'w']],
    $pipes, null, $env);
if (!is_resource($process)) throw new RuntimeException('C child unavailable');
$stdout = stream_get_contents($pipes[1]);
$stderr = stream_get_contents($pipes[2]);
fclose($pipes[1]);
fclose($pipes[2]);
$exit = proc_close($process);
$result = json_decode((string)$stdout, true);
if (!is_array($result)) {
    echo json_encode(['status' => 'redacted_child_error', 'exit' => $exit,
        'stderr' => $stderr === '' ? 'empty' : 'nonempty']), PHP_EOL;
    exit($exit === 0 ? 2 : $exit);
}
echo json_encode(['exit' => $exit, 'result' => $result,
    'stderr' => $stderr === '' ? 'empty' : 'nonempty'],
    JSON_UNESCAPED_SLASHES), PHP_EOL;
exit($exit);
