#!/usr/bin/python3
"""Fetch device config & LUKS key from config server, unlock /srv/kiosk, and sync configs."""

import base64
import binascii
from glob import glob
import hashlib
import json
import locale
import os
from pathlib import Path, PurePosixPath
import pwd
import shutil
import ssl
import subprocess
import sys
import time
import tomllib
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen


ETC = Path("/etc/kiosk-upgrade")
UNLOCK_CONF = ETC / "unlock.toml"
CERT_DIR = ETC / "unlock"
VAULT_IMAGE = Path("/var/lib/kiosk.luks")
MAPPER_NAME = "kiosk-vault"
MAPPER_DEV = Path(f"/dev/mapper/{MAPPER_NAME}")
MOUNT_POINT = Path("/srv/kiosk")
CONFIGS_ROOT = MOUNT_POINT / "configs"
SYSTEMD_RUN = Path("/run/systemd/system")
MAX_RESPONSE_BYTES = 4 * 1024 * 1024

SUBDIRS = (
    ("app", 0o755),
    ("app/chromium-profile", 0o700),
    ("data", 0o755),
    ("log", 0o755),
    ("configs", 0o755),
    ("containers", 0o700),
    ("wireguard", 0o700),
    ("openvpn", 0o700),
    ("openvpn/client", 0o700),
    ("ssl", 0o755),
    ("ssl/private", 0o700),
    ("kiosk-hw-srv", 0o700),
)

SUBDIR_OWNERS = {
    "app/chromium-profile": "kiosk",
}

# Legacy directories force-redirected into the encrypted /srv/kiosk vault.
# Tuple: (system_rel_dir, vault_rel_dir, mode)
LEGACY_DIR_LINKS = (
    ("etc/ssl/private", "ssl/private", 0o700),
    ("etc/wireguard", "wireguard", 0o700),
    ("etc/openvpn/client", "openvpn/client", 0o700),
    ("var/lib/kiosk-hw-srv", "kiosk-hw-srv", 0o700),
    ("var/lib/kiosk", "data", 0o755),
    ("var/log/kiosk", "log", 0o755),
)

ALLOWED_CONFIG_PREFIXES = (
    "/etc/ssl/private/",
    "/etc/openvpn/",
    "/etc/wireguard/",
    "/etc/default/",
    "/etc/kiosk/",
    "/var/lib/kiosk-hw-srv/",
    "/var/lib/kiosk/",
    "/var/log/kiosk/",
    "/srv/kiosk/",
)

PUBLIC_DIR_PREFIXES = (
    "/etc/default/",
    "/var/lib/kiosk/",
    "/var/log/kiosk/",
    "/srv/kiosk/",
)


class RevokedError(RuntimeError):
    """Device was explicitly rejected by the configuration server."""


def _fields(argv, marker, delimiter, first=False):
    values = []
    for line in subprocess.check_output(argv, timeout=10).split(b"\n"):
        if marker in line:
            values.append(line.split(delimiter, 2)[1])
            if first:
                break
    return b"\n".join(values).rstrip(b"\n")


def _dmi(record, key, first=False):
    return _fields(["dmidecode", "-t", record], key + b":", b":", first)


def _macs(net_dir):
    previous = locale.setlocale(locale.LC_COLLATE)
    try:
        locale.setlocale(locale.LC_COLLATE, "")
        addresses = sorted(glob(str(net_dir / "*/address")), key=locale.strxfrm)
    finally:
        locale.setlocale(locale.LC_COLLATE, previous)
    return b" ".join(b"".join(Path(path).read_bytes() for path in addresses).split())


def compute_hwid(net_dir=Path("/sys/class/net")):
    parts = [
        _dmi("bios", b"Version"),
        _dmi("baseboard", b"Manufacturer"),
        _dmi("baseboard", b"Product Name"),
        _dmi("processor", b"Version", first=True),
        _dmi("processor", b"ID", first=True),
        _macs(net_dir),
        _fields(
            ["udevadm", "info", "--query=all", "--name=/dev/sda"], b"ID_SERIAL=", b"="
        ),
    ]
    return hashlib.sha512(b"".join(reversed(parts)) + b"\n").hexdigest()


def first_mac_no_colons(net_dir=Path("/sys/class/net")):
    candidates = sorted(
        p for p in net_dir.iterdir() if p.name != "lo" and (p / "address").is_file()
    )
    physical = [p for p in candidates if (p / "device").exists()]
    chosen = physical or candidates
    if not chosen:
        raise RuntimeError("no network interface found for MAC address")
    mac = (chosen[0] / "address").read_text().strip().replace(":", "").upper()
    if not mac:
        raise RuntimeError(f"empty MAC address on {chosen[0].name}")
    return mac


def build_ssl_context(config, cert_dir=CERT_DIR):
    ca_cert = config.get("ca_cert")
    client_cert = config.get("client_cert")
    client_key = config.get("client_key")
    ctx = ssl.create_default_context()
    if ca_cert:
        ctx.load_verify_locations(cafile=str(cert_dir / ca_cert))
    if client_cert or client_key:
        if not (client_cert and client_key):
            raise ValueError("unlock.toml must specify both client_cert and client_key")
        ctx.load_cert_chain(
            certfile=str(cert_dir / client_cert), keyfile=str(cert_dir / client_key)
        )
    return ctx


def _read_error_description(err):
    try:
        raw = err.read(16384)
        payload = json.loads(raw)
        if isinstance(payload, dict):
            return payload.get("description") or payload.get("status") or ""
    except (OSError, ValueError):
        pass
    return ""


def request_config_once(config, hwid, ctx, cereal_mac=None):
    headers = {"Content-Type": "application/json"}
    if cereal_mac is not None:
        headers["ssl-dn"] = f"CN=kiosk-{cereal_mac}"
        body = b"{}"
    else:
        body = json.dumps({"hw_id": hwid}).encode()
    req = Request(
        config["url"],
        data=body,
        headers=headers,
        method="POST",
    )
    try:
        with urlopen(req, context=ctx, timeout=15) as resp:
            raw = resp.read(MAX_RESPONSE_BYTES + 1)
    except HTTPError as err:
        desc = _read_error_description(err)
        detail = f": {desc}" if desc else ""
        if err.code in {401, 403}:
            raise RevokedError(
                f"config server rejected device (HTTP {err.code}{detail})"
            ) from err
        raise RuntimeError(f"config server HTTP {err.code}{detail}") from err
    if len(raw) > MAX_RESPONSE_BYTES:
        raise RuntimeError(
            f"config server response exceeded {MAX_RESPONSE_BYTES} bytes"
        )
    data = json.loads(raw)
    if not isinstance(data, dict):
        raise RuntimeError("config server returned non-object JSON")
    status = data.get("status", "OK")
    if status in {"Unauthorized", "Revoked"}:
        raise RevokedError(
            f"config server rejected device: {data.get('description', status)}"
        )
    if status != "OK":
        desc = data.get("description")
        raise RuntimeError(
            f"config server returned status {status!r}" + (f" ({desc})" if desc else "")
        )
    key = data.get("pwd") or data.get("key")
    if not isinstance(key, str) or not key:
        raise RuntimeError("config server response missing pwd/key")
    configs = data.get("configs", [])
    if not isinstance(configs, list):
        raise RuntimeError("config server response configs must be a list")
    meta = {
        k: data[k] for k in ("deviceId", "newlyCreated", "vpnClientAddr") if k in data
    }
    return key, configs, meta


def fetch_config(config, hwid, cereal_mac=None, cert_dir=CERT_DIR):
    ctx = build_ssl_context(config, cert_dir=cert_dir)
    timeout = int(config.get("timeout_sec", 180))
    deadline = time.monotonic() + max(timeout, 1)
    while True:
        try:
            return request_config_once(config, hwid, ctx, cereal_mac=cereal_mac)
        except RevokedError:
            raise
        except (OSError, URLError, ValueError, RuntimeError) as err:
            if time.monotonic() >= deadline:
                raise RuntimeError(
                    f"timed out waiting for device config: {err}"
                ) from err
            print(f"Config request failed ({err}); retrying...", flush=True)
            time.sleep(3)


def ensure_vault_subdirs(mount_point=MOUNT_POINT):
    for name, mode in SUBDIRS:
        path = mount_point / name
        path.mkdir(mode=mode, exist_ok=True)
        os.chmod(path, mode)
        owner = SUBDIR_OWNERS.get(name)
        if owner:
            try:
                pw = pwd.getpwnam(owner)
            except KeyError:
                continue
            os.chown(path, pw.pw_uid, pw.pw_gid)


def open_and_mount(config, key):
    MOUNT_POINT.mkdir(mode=0o755, exist_ok=True)
    if not os.path.ismount(MOUNT_POINT):
        fresh = not VAULT_IMAGE.exists()
        if fresh:
            size_mb = int(config.get("vault_size_mb", 4096))
            fd = os.open(VAULT_IMAGE, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
            try:
                os.ftruncate(fd, size_mb * 1024 * 1024)
            finally:
                os.close(fd)
            subprocess.run(
                [
                    "cryptsetup",
                    "luksFormat",
                    "--type",
                    "luks2",
                    "--batch-mode",
                    str(VAULT_IMAGE),
                    "--key-file=-",
                ],
                input=key.encode(),
                check=True,
            )
        if not MAPPER_DEV.exists():
            subprocess.run(
                ["cryptsetup", "open", str(VAULT_IMAGE), MAPPER_NAME, "--key-file=-"],
                input=key.encode(),
                check=True,
            )
        if fresh:
            subprocess.run(
                ["mkfs.ext4", "-L", "kiosk-vault", str(MAPPER_DEV)], check=True
            )
        subprocess.run(
            ["mount", "-o", "defaults,noatime", str(MAPPER_DEV), str(MOUNT_POINT)],
            check=True,
        )
    ensure_vault_subdirs(MOUNT_POINT)


def validate_config_path(filename):
    if (
        not isinstance(filename, str)
        or not filename.startswith("/")
        or filename.endswith("/")
        or "\x00" in filename
    ):
        raise ValueError(f"invalid config filename: {filename!r}")
    parts = filename.split("/")[1:]
    if not parts or any(part in {"", ".", ".."} for part in parts):
        raise ValueError(f"unsafe config filename: {filename!r}")
    normalized = "/" + "/".join(parts)
    if not any(normalized.startswith(prefix) for prefix in ALLOWED_CONFIG_PREFIXES):
        raise ValueError(f"config filename outside allowed prefixes: {filename!r}")
    return PurePosixPath(normalized)


def _config_file_mode(name, path):
    normalized = str(path)
    if normalized.startswith(("/etc/default/", "/var/lib/kiosk/", "/var/log/kiosk/")):
        return 0o644
    if path.suffix == ".crt" and "key" not in str(name).lower():
        return 0o644
    return 0o600


def _config_dir_mode(path):
    normalized = str(path)
    if any(normalized.startswith(prefix) for prefix in PUBLIC_DIR_PREFIXES):
        return 0o755
    return 0o700


def _write_atomic(dest, payload, mode):
    tmp = dest.parent / f".{dest.name}.tmp.{os.getpid()}"
    fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, mode)
    try:
        with os.fdopen(fd, "wb") as f:
            f.write(payload)
            f.flush()
            os.fsync(f.fileno())
        os.chmod(tmp, mode)
        os.replace(tmp, dest)
    except BaseException:
        tmp.unlink(missing_ok=True)
        raise


def _symlink_atomic(link_path, target):
    tmp = link_path.parent / f".{link_path.name}.lnk.{os.getpid()}"
    tmp.unlink(missing_ok=True)
    os.symlink(target, tmp)
    try:
        os.replace(tmp, link_path)
    except BaseException:
        tmp.unlink(missing_ok=True)
        raise


def ensure_legacy_dir_symlinks(
    root_prefix=Path("/"), vault_mount=MOUNT_POINT, vault_target_base=MOUNT_POINT
):
    """Redirect legacy config/data/log directories into the encrypted vault."""
    for sys_rel, vault_rel, mode in LEGACY_DIR_LINKS:
        vault_dir = vault_mount / vault_rel
        vault_dir.mkdir(mode=mode, parents=True, exist_ok=True)
        os.chmod(vault_dir, mode)

        link_path = root_prefix / sys_rel
        link_target = vault_target_base / vault_rel
        if not link_path.parent.exists():
            link_path.parent.mkdir(parents=True, exist_ok=True)

        if link_path.is_symlink():
            if os.readlink(link_path) != str(link_target):
                _symlink_atomic(link_path, link_target)
            continue

        if link_path.exists():
            if not link_path.is_dir():
                raise NotADirectoryError(
                    f"expected directory or symlink at {link_path}"
                )
            for item in sorted(link_path.iterdir()):
                dest = vault_dir / item.name
                if not dest.exists():
                    shutil.move(str(item), str(dest))
            shutil.rmtree(link_path)
        os.symlink(link_target, link_path)


def _resolve_vault_destination(rel_target, vault_mount, configs_root):
    normalized = str(rel_target)
    if normalized.startswith("/srv/kiosk/"):
        return vault_mount / normalized.removeprefix("/srv/kiosk/"), False
    for sys_rel, vault_rel, _ in LEGACY_DIR_LINKS:
        prefix = f"/{sys_rel}/"
        if normalized.startswith(prefix):
            return vault_mount / vault_rel / normalized.removeprefix(prefix), False
    if normalized.startswith("/etc/openvpn/"):
        return vault_mount / "openvpn" / normalized.removeprefix("/etc/openvpn/"), True
    return configs_root / normalized.lstrip("/"), True


def apply_configs(
    configs,
    meta=None,
    root_prefix=Path("/"),
    vault_mount=MOUNT_POINT,
    configs_root=CONFIGS_ROOT,
    vault_target_base=None,
):
    if vault_target_base is None:
        vault_target_base = vault_mount
    ensure_legacy_dir_symlinks(
        root_prefix=root_prefix,
        vault_mount=vault_mount,
        vault_target_base=vault_target_base,
    )
    written = []
    if meta:
        _write_atomic(
            vault_mount / "device-meta.json",
            (json.dumps(meta, indent=2) + "\n").encode(),
            0o644,
        )
    for entry in configs:
        if not isinstance(entry, dict):
            raise ValueError("config entry must be a JSON object")
        name = entry.get("name", "")
        rel_target = validate_config_path(entry.get("filename"))
        raw_data = entry.get("data")
        if not isinstance(raw_data, str):
            raise ValueError(
                f"config {entry.get('filename')!r} missing base64 data string"
            )
        try:
            payload = base64.b64decode(raw_data, validate=True)
        except (binascii.Error, ValueError) as err:
            raise ValueError(f"invalid base64 payload for {rel_target}: {err}") from err

        dir_mode = _config_dir_mode(rel_target)
        file_mode = _config_file_mode(name, rel_target)
        vault_file, needs_file_symlink = _resolve_vault_destination(
            rel_target, vault_mount, configs_root
        )
        vault_file.parent.mkdir(mode=dir_mode, parents=True, exist_ok=True)
        os.chmod(vault_file.parent, dir_mode)
        _write_atomic(vault_file, payload, file_mode)

        if needs_file_symlink:
            rel_no_slash = str(rel_target).lstrip("/")
            sys_path = root_prefix / rel_no_slash
            if sys_path.exists() and not sys_path.is_symlink() and sys_path.is_dir():
                raise IsADirectoryError(
                    f"cannot replace directory with config symlink: {sys_path}"
                )
            if not sys_path.parent.exists():
                sys_path.parent.mkdir(mode=dir_mode, parents=True, exist_ok=True)
            link_target = vault_target_base / vault_file.relative_to(vault_mount)
            if sys_path.parent.resolve() != vault_file.parent.resolve():
                _symlink_atomic(sys_path, link_target)
        written.append(rel_target)

    # Legacy OpenVPN local.conf compatibility until the server config is updated.
    if PurePosixPath("/etc/openvpn/client.conf") in written:
        try:
            (vault_mount / "openvpn/client/local.conf").touch(mode=0o600, exist_ok=False)
        except FileExistsError:
            pass
    return written


def vpn_units_for_paths(paths):
    units = []
    for path in paths:
        if path.suffix != ".conf":
            continue
        if path.parent == PurePosixPath("/etc/openvpn"):
            units.append(f"openvpn@{path.stem}.service")
        elif path.parent == PurePosixPath("/etc/openvpn/client"):
            units.append(f"openvpn-client@{path.stem}.service")
        elif path.parent == PurePosixPath("/etc/wireguard"):
            units.append(f"wg-quick@{path.stem}.service")
    return list(dict.fromkeys(units))


def activate_vpn_units(paths):
    units = vpn_units_for_paths(paths)
    if not units or not SYSTEMD_RUN.is_dir():
        return
    for unit in units:
        active = (
            subprocess.run(
                ["systemctl", "is-active", "--quiet", "--", unit],
                check=False,
            ).returncode
            == 0
        )
        action = "restart" if active else "start"
        subprocess.run(["systemctl", action, "--no-block", "--", unit], check=False)


def main():
    if len(sys.argv) == 2 and sys.argv[1] == "--hwid":
        print(compute_hwid())
        return 0
    if not UNLOCK_CONF.is_file():
        return 0
    config = tomllib.loads(UNLOCK_CONF.read_text())
    if "url" not in config or not str(config["url"]).startswith("https://"):
        raise ValueError("unlock.toml requires an https:// url")
    if bool(config.get("use_cereal_header", False)):
        hwid, cereal_mac = None, first_mac_no_colons()
    else:
        hwid, cereal_mac = compute_hwid(), None
    key, configs, meta = fetch_config(config, hwid, cereal_mac=cereal_mac)
    open_and_mount(config, key)
    written = apply_configs(configs, meta=meta)
    activate_vpn_units(written)
    print(
        f"kiosk-unlock: mounted {MOUNT_POINT}, synced {len(written)} config(s)"
        + (f", deviceId={meta['deviceId']}" if "deviceId" in meta else ""),
        flush=True,
    )
    return 0


if __name__ == "__main__":
    try:
        sys.exit(main())
    except Exception as error:
        print(f"kiosk-unlock: {error}", file=sys.stderr)
        sys.exit(1)
