// The car's server updating itself (GET/POST /api/update, SELF_UPDATE=1 in // its .env): a topbar button shows up when main has a newer version that // passed CI; a click installs it (bin/update-maptool.sh on the host) and the // page reloads once the server answers with the new revision. const CHECK_MS = 10 * 60 * 1000; const RESTART_POLL_MS = 5000; export function setupUpdate(button, checkNow) { let latest = null; let timer = null; async function check(fresh = false) { clearTimeout(timer); try { const state = await (await fetch(`/api/update${fresh ? "?fresh=1" : ""}`, { cache: "no-store" })).json(); if (!state.enabled) return; if (checkNow) { checkNow.hidden = false; if (fresh) checkNow.textContent = state.available ? `Update ${state.latest} available ↑` : `Up to date (${state.current}) — check again`; } latest = state.latest; button.hidden = !state.available; button.textContent = `⟳ ${state.latest}`; button.title = `A new version (${state.latest}, now ${state.current}) — click to update; the app restarts for about a minute`; if (state.status?.state === "failed") button.title += `\nThe last update failed: ${state.status.message}`; timer = setTimeout(check, CHECK_MS); } catch { timer = setTimeout(check, CHECK_MS); } } checkNow?.addEventListener("click", () => check(true)); async function waitForRestart(revision) { try { const health = await (await fetch("/api/health", { cache: "no-store" })).json(); if (health.revision !== revision) return window.location.reload(); } catch { // restarting: not answering for a while } setTimeout(() => waitForRestart(revision), RESTART_POLL_MS); } button.addEventListener("click", async () => { if (!window.confirm(`Update to ${latest}? The app restarts — about a minute without it.`)) return; button.disabled = true; button.textContent = "Updating…"; const response = await fetch("/api/update", { method: "POST" }); const data = await response.json().catch(() => ({})); if (!response.ok) { window.alert(data.error || `Update failed (${response.status})`); button.disabled = false; return check(); } const revision = (await (await fetch("/api/health")).json()).revision; waitForRestart(revision); }); check(); }