<?php
declare(strict_types=1);

// This is the only public PHP file. The installer places all application code,
// config, keys, state, and logs in SAFETUN_PRIVATE_DIR outside public_html.
$privateRoot = getenv('SAFETUN_PRIVATE_DIR');
if (!is_string($privateRoot) || $privateRoot === '') {
    $configured = $_SERVER['SAFETUN_PRIVATE_DIR'] ?? null;
    $privateRoot = is_string($configured) && $configured !== ''
        ? $configured
        : dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'safetun-private';
}
$bootstrap = rtrim($privateRoot, '/\\') . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR . 'bootstrap.php';
$realBootstrap = realpath($bootstrap);
$realDocroot = isset($_SERVER['DOCUMENT_ROOT']) && is_string($_SERVER['DOCUMENT_ROOT'])
    ? realpath($_SERVER['DOCUMENT_ROOT']) : false;
$insideDocroot = false;
if (is_string($realBootstrap) && is_string($realDocroot)) {
    $candidate = PHP_OS_FAMILY === 'Windows' ? strtolower($realBootstrap) : $realBootstrap;
    $prefix = rtrim(PHP_OS_FAMILY === 'Windows' ? strtolower($realDocroot) : $realDocroot, '/\\') . DIRECTORY_SEPARATOR;
    $insideDocroot = str_starts_with($candidate, $prefix);
}
if (!is_string($realBootstrap) || !is_file($realBootstrap) || is_link($bootstrap) || $insideDocroot) {
    $requestBytes = random_bytes(16);
    $requestBytes[6] = chr((ord($requestBytes[6]) & 0x0f) | 0x40);
    $requestBytes[8] = chr((ord($requestBytes[8]) & 0x3f) | 0x80);
    $requestHex = bin2hex($requestBytes);
    $requestId = substr($requestHex, 0, 8) . '-' . substr($requestHex, 8, 4) . '-'
        . substr($requestHex, 12, 4) . '-' . substr($requestHex, 16, 4) . '-' . substr($requestHex, 20);
    http_response_code(503);
    header('Content-Type: application/json; charset=utf-8');
    header('Cache-Control: no-store');
    header('X-Content-Type-Options: nosniff');
    header('X-Request-ID: ' . $requestId);
    echo json_encode([
        'error' => ['code' => 'SERVICE_UNAVAILABLE', 'request_id' => $requestId],
        'request_id' => $requestId,
    ], JSON_UNESCAPED_SLASHES) . "\n";
    exit;
}
require $realBootstrap;
