<?php

declare(strict_types=1);

$baseDir = __DIR__;
$configFile = $baseDir . "/config.php";
$manifestFile = $baseDir . "/manifest.json";
$packagesDir = $baseDir . "/packages";

if (is_file($configFile)) {
    require_once $configFile;
}

if (session_status() === PHP_SESSION_NONE) {
    ini_set("session.use_strict_mode", "1");
    ini_set("session.cookie_httponly", "1");
    ini_set("session.cookie_samesite", "Lax");
    session_start();
}

$messages = [];
$errors = [];

function updateManageEscape($value): string
{
    return htmlspecialchars((string) $value, ENT_QUOTES, "UTF-8");
}

function updateManageVersionIsValid(string $version): bool
{
    return preg_match('/^v\d+\.\d+\.\d+$/', $version) === 1;
}

function updateManagePasswordConfigured(): bool
{
    return defined("UPDATE_SERVER_PASSWORD_HASH") || defined("UPDATE_SERVER_PASSWORD");
}

function updateManagePasswordMatches(string $password): bool
{
    if (defined("UPDATE_SERVER_PASSWORD_HASH")) {
        return password_verify($password, (string) UPDATE_SERVER_PASSWORD_HASH);
    }

    if (defined("UPDATE_SERVER_PASSWORD")) {
        return hash_equals((string) UPDATE_SERVER_PASSWORD, $password);
    }

    return false;
}

function updateManageIsLoggedIn(): bool
{
    return !empty($_SESSION["update_server_logged_in"]);
}

function updateManageCsrfToken(): string
{
    if (empty($_SESSION["update_server_csrf_token"])) {
        $_SESSION["update_server_csrf_token"] = bin2hex(random_bytes(32));
    }

    return $_SESSION["update_server_csrf_token"];
}

function updateManageCsrfIsValid(string $token): bool
{
    return !empty($_SESSION["update_server_csrf_token"]) &&
        hash_equals($_SESSION["update_server_csrf_token"], $token);
}

function updateManageEnsureDirectory(string $dir): void
{
    if (!is_dir($dir) && !mkdir($dir, 02775, true) && !is_dir($dir)) {
        throw new RuntimeException("Directory cannot be created: " . $dir);
    }

    @chmod($dir, 02775);
}

function updateManageReadManifest(string $manifestFile): array
{
    if (!is_file($manifestFile)) {
        return ["latest" => "", "releases" => []];
    }

    $decoded = json_decode((string) file_get_contents($manifestFile), true);
    if (!is_array($decoded)) {
        throw new RuntimeException("Manifest is not valid JSON.");
    }

    return [
        "latest" => trim((string) ($decoded["latest"] ?? "")),
        "releases" => isset($decoded["releases"]) && is_array($decoded["releases"])
            ? $decoded["releases"]
            : [],
    ];
}

function updateManageWriteManifest(string $manifestFile, array $manifest): void
{
    $json = json_encode(
        $manifest,
        JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE,
    );
    if ($json === false) {
        throw new RuntimeException("Manifest cannot be encoded.");
    }

    $tmpFile = $manifestFile . ".tmp";
    if (file_put_contents($tmpFile, $json . PHP_EOL, LOCK_EX) === false) {
        throw new RuntimeException("Manifest cannot be written.");
    }

    @chmod($tmpFile, 0664);
    if (!rename($tmpFile, $manifestFile)) {
        @unlink($tmpFile);
        throw new RuntimeException("Manifest cannot be saved.");
    }

    @chmod($manifestFile, 0664);
}

function updateManagePackageFileName(string $version): string
{
    return "psa-orderform-" . $version . ".zip";
}

function updateManageUploadedFileIsZip(array $file): bool
{
    $name = strtolower((string) ($file["name"] ?? ""));
    $tmpName = (string) ($file["tmp_name"] ?? "");

    if (!str_ends_with($name, ".zip") || !is_uploaded_file($tmpName)) {
        return false;
    }

    $handle = fopen($tmpName, "rb");
    if ($handle === false) {
        return false;
    }

    $signature = fread($handle, 4);
    fclose($handle);

    return $signature === "PK\x03\x04" || $signature === "PK\x05\x06" || $signature === "PK\x07\x08";
}

function updateManagePublishUpload(
    string $version,
    array $file,
    string $manifestFile,
    string $packagesDir,
): void {
    if (!updateManageVersionIsValid($version)) {
        throw new RuntimeException("Version must use the format vX.Y.Z.");
    }

    if (($file["error"] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
        throw new RuntimeException("Upload failed with error code " . (string) ($file["error"] ?? "unknown") . ".");
    }

    if (!updateManageUploadedFileIsZip($file)) {
        throw new RuntimeException("Uploaded file must be a ZIP package.");
    }

    updateManageEnsureDirectory($packagesDir);

    $fileName = updateManagePackageFileName($version);
    $targetPath = $packagesDir . DIRECTORY_SEPARATOR . $fileName;
    if (!move_uploaded_file((string) $file["tmp_name"], $targetPath)) {
        throw new RuntimeException("Uploaded package cannot be stored.");
    }

    @chmod($targetPath, 0664);

    $sha256 = strtolower(hash_file("sha256", $targetPath) ?: "");
    $size = filesize($targetPath);
    if (!preg_match('/^[a-f0-9]{64}$/', $sha256) || $size === false || $size <= 0) {
        @unlink($targetPath);
        throw new RuntimeException("Stored package could not be verified.");
    }

    $manifest = updateManageReadManifest($manifestFile);
    $manifest["latest"] = $version;
    $manifest["releases"][$version] = [
        "version" => $version,
        "package" => "packages/" . $fileName,
        "sha256" => $sha256,
        "size" => $size,
        "published_at" => date(DATE_ATOM),
    ];

    ksort($manifest["releases"]);
    updateManageWriteManifest($manifestFile, $manifest);
}

function updateManageSetLatest(string $version, string $manifestFile): void
{
    if (!updateManageVersionIsValid($version)) {
        throw new RuntimeException("Invalid release version.");
    }

    $manifest = updateManageReadManifest($manifestFile);
    if (!isset($manifest["releases"][$version])) {
        throw new RuntimeException("Release is not present in the manifest.");
    }

    $manifest["latest"] = $version;
    updateManageWriteManifest($manifestFile, $manifest);
}

function updateManageDeleteRelease(
    string $version,
    string $manifestFile,
    string $baseDir,
): void {
    if (!updateManageVersionIsValid($version)) {
        throw new RuntimeException("Invalid release version.");
    }

    $manifest = updateManageReadManifest($manifestFile);
    if (!isset($manifest["releases"][$version])) {
        throw new RuntimeException("Release is not present in the manifest.");
    }

    $package = trim((string) ($manifest["releases"][$version]["package"] ?? ""));
    unset($manifest["releases"][$version]);
    if ($manifest["latest"] === $version) {
        $manifest["latest"] = "";
    }

    updateManageWriteManifest($manifestFile, $manifest);

    if ($package !== "" && !str_contains($package, "\0") && !str_starts_with($package, "/")) {
        $packagePath = realpath($baseDir . "/" . $package);
        $packagesPath = realpath($baseDir . "/packages");
        if (
            $packagePath !== false &&
            $packagesPath !== false &&
            str_starts_with($packagePath, $packagesPath . DIRECTORY_SEPARATOR) &&
            is_file($packagePath)
        ) {
            unlink($packagePath);
        }
    }
}

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $action = (string) ($_POST["action"] ?? "");

    if ($action === "login") {
        if (!updateManagePasswordConfigured()) {
            $errors[] = "No password is configured.";
        } elseif (updateManagePasswordMatches((string) ($_POST["password"] ?? ""))) {
            session_regenerate_id(true);
            $_SESSION["update_server_logged_in"] = true;
            $messages[] = "Logged in.";
        } else {
            $errors[] = "Wrong password.";
        }
    } elseif ($action === "logout") {
        unset($_SESSION["update_server_logged_in"], $_SESSION["update_server_csrf_token"]);
        $messages[] = "Logged out.";
    } elseif (!updateManageIsLoggedIn()) {
        $errors[] = "Login required.";
    } elseif (!updateManageCsrfIsValid((string) ($_POST["csrf_token"] ?? ""))) {
        $errors[] = "Invalid token. Please reload the page and try again.";
    } else {
        try {
            if ($action === "upload") {
                updateManagePublishUpload(
                    trim((string) ($_POST["version"] ?? "")),
                    $_FILES["package"] ?? [],
                    $manifestFile,
                    $packagesDir,
                );
                $messages[] = "Release uploaded and published.";
            } elseif ($action === "set_latest") {
                updateManageSetLatest(trim((string) ($_POST["version"] ?? "")), $manifestFile);
                $messages[] = "Latest release updated.";
            } elseif ($action === "delete") {
                updateManageDeleteRelease(trim((string) ($_POST["version"] ?? "")), $manifestFile, $baseDir);
                $messages[] = "Release deleted.";
            }
        } catch (Throwable $exception) {
            $errors[] = $exception->getMessage();
        }
    }
}

try {
    $manifest = updateManageReadManifest($manifestFile);
} catch (Throwable $exception) {
    $manifest = ["latest" => "", "releases" => []];
    $errors[] = $exception->getMessage();
}

$releases = $manifest["releases"];
krsort($releases);

?>
<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Update Management</title>
</head>
<body>
    <h1>Update Management</h1>

    <?php foreach ($messages as $message): ?>
        <p><strong><?php echo updateManageEscape($message); ?></strong></p>
    <?php endforeach; ?>

    <?php foreach ($errors as $error): ?>
        <p><strong>Error:</strong> <?php echo updateManageEscape($error); ?></p>
    <?php endforeach; ?>

    <?php if (!updateManageIsLoggedIn()): ?>
        <form method="POST">
            <input type="hidden" name="action" value="login">
            <p>
                <label for="password">Password</label><br>
                <input type="password" id="password" name="password" required>
            </p>
            <button type="submit">Login</button>
        </form>
    <?php else: ?>
        <form method="POST">
            <input type="hidden" name="action" value="logout">
            <button type="submit">Logout</button>
        </form>

        <h2>Upload release</h2>
        <form method="POST" enctype="multipart/form-data">
            <input type="hidden" name="action" value="upload">
            <input type="hidden" name="csrf_token" value="<?php echo updateManageEscape(updateManageCsrfToken()); ?>">
            <p>
                <label for="version">Version</label><br>
                <input type="text" id="version" name="version" required placeholder="v1.3.3" pattern="v[0-9]+\.[0-9]+\.[0-9]+">
            </p>
            <p>
                <label for="package">ZIP package</label><br>
                <input type="file" id="package" name="package" accept=".zip,application/zip" required>
            </p>
            <button type="submit">Upload and publish</button>
        </form>

        <h2>Current manifest</h2>
        <p>Latest: <?php echo updateManageEscape($manifest["latest"] !== "" ? $manifest["latest"] : "none"); ?></p>
        <p>Manifest endpoint: <a href="manifest.php">manifest.php</a></p>

        <?php if (empty($releases)): ?>
            <p>No releases configured.</p>
        <?php else: ?>
            <table border="1" cellpadding="6" cellspacing="0">
                <thead>
                    <tr>
                        <th>Version</th>
                        <th>Package</th>
                        <th>SHA-256</th>
                        <th>Size</th>
                        <th>Published</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($releases as $version => $release): ?>
                        <tr>
                            <td><?php echo updateManageEscape($version); ?></td>
                            <td><?php echo updateManageEscape($release["package"] ?? ""); ?></td>
                            <td><?php echo updateManageEscape($release["sha256"] ?? ""); ?></td>
                            <td><?php echo updateManageEscape($release["size"] ?? ""); ?></td>
                            <td><?php echo updateManageEscape($release["published_at"] ?? ""); ?></td>
                            <td>
                                <?php if ($manifest["latest"] !== $version): ?>
                                    <form method="POST" style="display:inline">
                                        <input type="hidden" name="action" value="set_latest">
                                        <input type="hidden" name="csrf_token" value="<?php echo updateManageEscape(updateManageCsrfToken()); ?>">
                                        <input type="hidden" name="version" value="<?php echo updateManageEscape($version); ?>">
                                        <button type="submit">Set latest</button>
                                    </form>
                                <?php endif; ?>
                                <form method="POST" style="display:inline" onsubmit="return confirm('Delete this release?');">
                                    <input type="hidden" name="action" value="delete">
                                    <input type="hidden" name="csrf_token" value="<?php echo updateManageEscape(updateManageCsrfToken()); ?>">
                                    <input type="hidden" name="version" value="<?php echo updateManageEscape($version); ?>">
                                    <button type="submit">Delete</button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    <?php endif; ?>
</body>
</html>
