<?php

declare(strict_types=1);

/*
 * Atlas NGL local map endpoint.
 *
 * The map is a same-origin, static renderer. It intentionally avoids
 * bootstrapping the legacy LiveZilla runtime.
 */

$method =
    strtoupper(
        (string)(
            $_SERVER['REQUEST_METHOD']
            ?? 'GET'
        )
    );

if (
    $method !== 'GET' &&
    $method !== 'HEAD'
) {
    header('Allow: GET, HEAD');
    http_response_code(405);
    exit;
}

$template =
    __DIR__ .
    '/templates/map.tpl';

$templateDirectory =
    realpath(
        __DIR__ .
        '/templates'
    );

$templatePath =
    realpath($template);

$expectedTemplateHash =
    '73f26ecebee5c3c32a631dbb101778a953f25ce4fb6eda27f871ef56d5c818e4';

if (
    !is_string($templateDirectory) ||
    !is_string($templatePath) ||
    dirname($templatePath) !== $templateDirectory ||
    !is_file($templatePath) ||
    is_link($template) ||
    !hash_equals(
        $expectedTemplateHash,
        hash_file(
            'sha256',
            $templatePath
        )
    )
) {
    http_response_code(503);
    exit;
}

$length =
    filesize($templatePath);

if (
    !is_int($length) ||
    $length < 1 ||
    $length > 1048576
) {
    http_response_code(503);
    exit;
}

header(
    'Content-Type: text/html; charset=UTF-8'
);

header(
    'Content-Security-Policy: ' .
    "default-src 'none'; " .
    "img-src 'self' data:; " .
    "style-src 'self' 'unsafe-inline'; " .
    "script-src 'unsafe-inline'; " .
    "frame-ancestors 'self'; " .
    "base-uri 'none'; " .
    "form-action 'none'"
);

header('X-Frame-Options: SAMEORIGIN');
header('X-Content-Type-Options: nosniff');
header('Referrer-Policy: no-referrer');
header('Cross-Origin-Resource-Policy: same-origin');
header('Cache-Control: no-store, max-age=0');
header('Content-Length: ' . $length);

if ($method === 'HEAD') {
    exit;
}

$sent =
    readfile($templatePath);

if (
    $sent === false ||
    $sent !== $length
) {
    throw new RuntimeException(
        'Unable to deliver Atlas map template.'
    );
}

exit;