<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2019 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------

use think\App;

// [ 应用入口文件 ]

if (version_compare(PHP_VERSION, '8.2.0', '<') || version_compare(PHP_VERSION, '8.3.0', '>=')) {
    exit('请使用 PHP 8.2 版本');
}

/*
 * 完整生产包会携带签名组件清单。入口保持明文，在任何加密 PHP 文件
 * 执行前拦截未加载 Loader 的请求；本地开发树没有清单，因此不影响开发。
 */
$releaseManifest = __DIR__ . '/../config/site_manifest.dat';
$releaseLoaderFiles = glob(__DIR__ . '/../app/loader/swoole_loader*.{so,dll}', GLOB_BRACE) ?: [];
$isProtectedRelease = is_file($releaseManifest)
    || $releaseLoaderFiles !== []
    || (defined('ENTROPY_SW_BUILD') && ENTROPY_SW_BUILD);
$requestPath = parse_url((string)($_SERVER['REQUEST_URI'] ?? '/'), PHP_URL_PATH);
$requestPath = is_string($requestPath) ? trim($requestPath, '/') : '';
$requestPath = preg_replace('#^index\.php/?#i', '', $requestPath) ?? $requestPath;

// Nginx may rewrite the request to index.php while preserving the original
// ThinkPHP path in PATH_INFO or the legacy `s` query parameter.
if ($requestPath === '' || $requestPath === 'index.php') {
    $pathInfo = trim((string)($_SERVER['PATH_INFO'] ?? ''), '/');
    $queryPath = trim((string)($_GET['s'] ?? ''), '/');
    if ($pathInfo !== '' && $pathInfo !== 'index.php') {
        $requestPath = ltrim(rawurldecode($pathInfo), '/');
    } elseif ($queryPath !== '' && $queryPath !== 'index.php') {
        $requestPath = ltrim(rawurldecode($queryPath), '/');
    }
    $requestPath = preg_replace('#^index\.php/?#i', '', $requestPath) ?? $requestPath;
}

$isLoaderHelperRequest = $requestPath === 'swoole_loader_helper.php';
$isInstallationRequest = $requestPath === 'install'
    || str_starts_with($requestPath, 'install/')
    || $requestPath === 'api/install'
    || str_starts_with($requestPath, 'api/install/');

// The helper is the only public entry that must remain reachable while the
// Loader is missing. Every other request in a protected release checks the
// actual PHP-FPM environment first, including /install.
if (PHP_SAPI !== 'cli' && $isProtectedRelease && !$isLoaderHelperRequest) {
    // License files are no longer required. Only the Loader extension must be loaded.
    if (!extension_loaded('swoole_loader')) {
        header('Location: /swoole_loader_helper.php', true, 302);
        exit;
    }
}

require __DIR__ . '/../vendor/autoload.php';

// Reject a stale or damaged protected release before ThinkPHP creates the
// request pipeline. This keeps the failure path independent of view
// rendering, route loading, and middleware execution on Loader 3.2.
if (PHP_SAPI !== 'cli' && $isProtectedRelease && !$isInstallationRequest && !$isLoaderHelperRequest) {
    $manifest = is_file($releaseManifest)
        ? json_decode((string)file_get_contents($releaseManifest), true)
        : null;
    $manifestValid = is_array($manifest)
        && \app\service\SettlementReceiptService::verify($manifest);

    if (!$manifestValid) {
        http_response_code(403);
        header('Content-Type: text/html; charset=UTF-8');
        header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
        header('X-Entropy-Access-State: blocked');
        echo '<!doctype html><html lang="zh-CN"><head><meta charset="utf-8">'
            . '<meta name="viewport" content="width=device-width, initial-scale=1">'
            . '<meta name="robots" content="noindex,nofollow">'
            . '<title>服务暂不可用</title>'
            . '<style>html,body{margin:0;min-height:100%;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif;background:#f6f8fc;color:#1b2437}body{min-height:100vh;display:grid;place-items:center;padding:24px;box-sizing:border-box}main{width:min(100%,520px);box-sizing:border-box;padding:42px 32px;text-align:center;border:1px solid #e5eaf2;border-radius:8px;background:#fff;box-shadow:0 12px 32px rgba(30,59,112,.08)}h1{margin:0;font-size:24px;line-height:1.45}p{margin:14px 0 0;line-height:1.8;color:#5f6c82}</style>'
            . '</head><body><main><h1>服务暂不可用</h1><p>服务状态校验失败，请联系系统管理员。</p><p>请重新部署完整版本后再访问。</p></main></body></html>';
        exit;
    }
}

// 执行 HTTP 应用并响应
$http = (new App())->http;

$response = $http->run();

$response->send();

$http->end($response);
