<!DOCTYPE html>
<html>
<?php
/**
 * link-menu-system :: Canary Router (public start page)  ::  lms 7.1FBpaR
 *
 * Author     smisco <info@smisco.biz>
 * Copyright  (C) 2026 smisco
 * Website    https://smisco.biz/lms
 *
 * The "lms <build>.<ts6>" token above is the version stamp; keep it in lockstep
 * with the LMS_VERSION constant below.
 */
define('LMS_VERSION', '7.1FBpaR');
$configFile = 'router-config.json';
if (!file_exists($configFile)) {
    $defaultConfig = [
        "_lms_version" => LMS_VERSION, // ties this data file to the code that generated it
        // Meaningful placeholders -- edit per install (see README). The router is a
        // 3-step dance: this page (router_url) loads, probes the canary, then redirects
        // to internal_url (canary loaded = in-house) or external_url (canary failed/
        // timed out = off-network). router_url is informational/documentation.
        "external_url" => "https://public-fallback.example.com/",
        "router_url"   => "https://router.example.com/",
        "internal_url" => "https://internal-portal.example.com/",
        "canary_image" => "https://internal-portal.example.com/canary.png"
    ];
    file_put_contents($configFile, json_encode($defaultConfig, JSON_PRETTY_PRINT));
}
$config = json_decode(file_get_contents($configFile), true);

// Demo override: router/?demo=external simulates an off-network device by probing a canary
// that won't resolve (onerror fires -> external fallback). ?demo=internal (or no param)
// probes the real canary. Lets the marketing page demo both branches without touching the
// real canary file. Harmless in production: nobody appends ?demo=external to a start page.
$canaryUrl = $config['canary_image'];
if (($_GET['demo'] ?? '') === 'external') {
    $canaryUrl = rtrim($config['internal_url'], '/') . '/__demo_no_canary__.png';
}
?>
<head>
    <title>LMS Router</title>
    <script>
        const externalUrl = <?= json_encode($config['external_url']) ?>;
        const routerUrl   = <?= json_encode($config['router_url'] ?? '') ?>;
        const internalUrl = <?= json_encode($config['internal_url']) ?>;
        const canaryUrl   = <?= json_encode($canaryUrl) ?>;
        
        let timeout = setTimeout(() => {
            console.log("Canary timed out - redirecting external");
            window.location.replace(externalUrl);
        }, 3000);

        let canary = new Image();
        canary.onload = function() {
            console.log("Canary found - redirecting internal");
            clearTimeout(timeout);
            window.location.replace(internalUrl);
        };
        canary.onerror = function() {
            console.log("Canary unreachable - redirecting external");
            clearTimeout(timeout);
            window.location.replace(externalUrl);
        };
        canary.src = canaryUrl + "?t=" + new Date().getTime();
    </script>
</head>
<body>
    <!-- This page intentionally left blank. -->
</body>
</html>
