#!/usr/bin/python3
"""Launch the configured kiosk browser on Wayland, or show a non-interactive diagnostic screen."""

import base64
import hashlib
import json
import os
from pathlib import Path
import shutil
import socket
import sys
import tempfile
from urllib.parse import urlsplit


APP_OVERRIDE = Path("/srv/kiosk/app/run-application")
DEFAULT_KIOSK = Path("/etc/default/kiosk")
PROFILE_DIR = Path("/srv/kiosk/app/chromium-profile")
DIAGNOSTIC = "/usr/libexec/kiosk-platform/kiosk-diagnostic-screen"
BROWSER_CANDIDATES = ("/usr/bin/ungoogled-chromium", "/usr/bin/chromium")
IDLE_EXTENSION = Path("/usr/share/kiosk-platform/idle-extension")


def read_start_url(path=DEFAULT_KIOSK):
    if not path.is_file():
        return None
    for raw_line in path.read_text(encoding="utf-8", errors="replace").splitlines():
        line = raw_line.strip()
        if not line or line.startswith("#") or "=" not in line:
            continue
        key, val = line.split("=", 1)
        if key.strip() not in {"HOMEPAGE", "URL", "KIOSK_URL", "START_URL"}:
            continue
        val = val.strip()
        if len(val) >= 2 and val[0] == val[-1] and val[0] in {'"', "'"}:
            val = val[1:-1]
        try:
            parsed = urlsplit(val)
            if (parsed.scheme in {"http", "https"} and parsed.hostname
                    and parsed.username is None and not any(c.isspace() for c in val)):
                return val
        except ValueError:
            continue
    return None


def find_browser():
    for candidate in BROWSER_CANDIDATES:
        if os.access(candidate, os.X_OK):
            return candidate
    for name in ("ungoogled-chromium", "chromium"):
        found = shutil.which(name)
        if found:
            return found
    return None


def browser_command(browser, url):
    args = [
        browser,
        "--ozone-platform=wayland",
        "--kiosk",
        "--no-first-run",
        "--no-default-browser-check",
        f"--user-data-dir={PROFILE_DIR}",
    ]
    if (IDLE_EXTENSION / "manifest.json").is_file():
        args.append(f"--disable-extensions-except={IDLE_EXTENSION}")
    else:
        args.append("--disable-extensions")
    return [*args, "--", url]


def profile_in_use(profile_dir):
    try:
        host, pid = os.readlink(profile_dir / "SingletonLock").rsplit("-", 1)
        if host != socket.gethostname() or int(pid) <= 0:
            return True
        os.kill(int(pid), 0)
    except (FileNotFoundError, ProcessLookupError):
        return False
    except (OSError, ValueError, OverflowError):
        return True
    return True


def refresh_idle_worker(profile_dir, extension_dir):
    profile = profile_dir / "Default"
    database = profile / "Service Worker/Database"
    if not database.is_dir() or profile_in_use(profile_dir):
        return

    try:
        manifest = json.loads((extension_dir / "manifest.json").read_text(encoding="utf-8"))
        digest = hashlib.sha256(base64.b64decode(manifest["key"], validate=True)).hexdigest()
        extension_id = digest[:32].translate(str.maketrans("0123456789abcdef", "abcdefghijklmnop"))
        installed_version = manifest["version"]
        prefs = json.loads((profile / "Preferences").read_text(encoding="utf-8"))
        registered_version = prefs["extensions"]["settings"][extension_id]["service_worker_registration_info"]["version"]
    except (OSError, ValueError, TypeError, KeyError):
        return
    if not all(isinstance(version, str) and version for version in (installed_version, registered_version)):
        return
    if registered_version == installed_version:
        return

    # On this Chromium build, a new unpacked manifest can still run an old
    # registered worker. Let Chromium recreate the registration database; keep
    # a backup and leave the rest of the profile, including CacheStorage, alone.
    try:
        backup = Path(tempfile.mkdtemp(prefix="kiosk-idle-worker-backup-", dir=profile))
        database.rename(backup / "Database")
    except OSError as error:
        print(f"Kiosk idle: could not back up the service worker database: {error}", file=sys.stderr)
    else:
        print(f"Kiosk idle: rebuilding service worker registrations; backup: {backup}", file=sys.stderr)


def main():
    if APP_OVERRIDE.is_file() and os.access(APP_OVERRIDE, os.X_OK):
        os.execv(str(APP_OVERRIDE), [str(APP_OVERRIDE)])

    url = read_start_url()
    browser = find_browser()
    if not url or not browser:
        os.execv(DIAGNOSTIC, [DIAGNOSTIC])

    PROFILE_DIR.mkdir(parents=True, exist_ok=True)
    refresh_idle_worker(PROFILE_DIR, IDLE_EXTENSION)
    env = {**os.environ, "KIOSK_IDLE_HOMEPAGE": url}
    os.execve(browser, browser_command(browser, url), env)


if __name__ == "__main__":
    main()
