<?php
declare(strict_types=1);

// Build a self-contained private source tree. This script never connects to a DB.
$target = $argv[1] ?? '';
if (!preg_match('~^/tmp/zhct-odbc-table-[A-Za-z0-9]{8}$~D', $target)
    || !is_dir($target) || is_link($target)
    || (fileperms($target) & 0777) !== 0700
    || count(scandir($target)) !== 2) {
    throw new RuntimeException('Fresh mode-0700 private target required');
}
$sourceRoot = dirname(__DIR__, 3);
$files = [
    'work_ai_api/2026-09-30-dm8-interface-acceptance/'
        . 'parallel-odbc-synthetic-table/SyntheticTableAcceptance.draft.php'
        => '947438cf4efa073b1c6348033cb31dd382668298f50532639f840b181aa22a1d',
    'work_ai_api/2026-09-30-dm8-interface-acceptance/'
        . 'parallel-odbc-synthetic-table/PackageLoadTest.php'
        => 'ed9f996157747ab93ce3f066c23f38c78ca7621949308a26472c104e6f1ad56c',
    'work_ai_api/2026-09-30-dm8-interface-acceptance/'
        . 'parallel-odbc-app-connector/PrivateOdbcDm.php'
        => 'b9b0a3d3fd342f0b7efec20b00d3961b556c67ee56affac1359b6cc24cf04b05',
    'work_ai_api/2026-09-30-dm8-interface-acceptance/'
        . 'parallel-odbc-typed-statement/TypedStatement.php'
        => 'c012f50e66f98587676dbcbb84bf08e4f6c4753f675e0cc6fec62aa9b021b97c',
    'work_store/apifox/2026-09-30-dm8-interface-acceptance/'
        . 'parallel-odbc-typed-fetch/TypedFetchNormalizer.php'
        => 'ae240ec2a1b4e07f2e9f89ff8347dbdb5beca806e7c4136ab4116d928e495035',
];
umask(0077);
foreach ($files as $relative => $sha256) {
    $source = $sourceRoot . '/' . $relative;
    if (!is_file($source) || hash_file('sha256', $source) !== $sha256) {
        throw new RuntimeException('Approved source hash mismatch');
    }
}
$copied = [];
foreach ($files as $relative => $sha256) {
    $destination = $target . '/zhctprompt/' . $relative;
    $directory = dirname($destination);
    if (!is_dir($directory) && !mkdir($directory, 0700, true)) {
        throw new RuntimeException('Unable to create private package directory');
    }
    if (!copy($sourceRoot . '/' . $relative, $destination)
        || !chmod($destination, 0600)
        || hash_file('sha256', $destination) !== $sha256) {
        throw new RuntimeException('Private package copy or hash mismatch');
    }
    $copied[$relative] = $sha256;
}
echo json_encode(['status' => 'private-package-complete',
    'root' => $target . '/zhctprompt', 'files' => $copied],
    JSON_UNESCAPED_SLASHES), PHP_EOL;
