#!/usr/bin/env python3
# summary: Match the sign-in screen to your desktop.
"""starchaser greeter sync: keep the login screen looking like your desktop.

The login screen runs as the greeter account, which can't read anyone's home, so this copies what it needs into
/var/lib/starchaser/greeter (created by the desktop setup; every account that uses the desktop runs this, so the
folder can be shared by the group of desktop users, and whoever synced last decides the look):
    theme.json          the active theme, with each monitor's wallpaper pointing at the copy below, plus
                        "clock24" (the taskbar's 24-hour clock choice, so the login clock matches) and
                        "text_scale" (Settings > Accessibility's text size, so the login screen's text matches)
                        and "screen_reader" (true when speech is on, so the login screen starts the screen reader)
    wall-<output>.<ext> the wallpaper each monitor shows
    monitors.tsv        the monitor layout (Settings > Displays), so the login screen uses the same arrangement:
                        plain values only, one screen per line. Never Lua: the login screen would run it. The
                        login screen checks every value again itself before using it (this folder is yours).
    users               the people who've used this desktop, in the order they first did (ordering only)
    last-user           who logged in last (picked first on the login screen)
    mc-login.css        the theme's colors for Mission Control's web sign-in page (linked from its branding folder):
                        CSS custom properties only, each value a checked #rrggbb (or a plain number for the panel
                        opacity), never any other text from the theme file
Run by the starchaser-greeter-sync.path user unit whenever the theme, wallpaper or monitors change.
"""
import json
import os
import pwd
import re
import shutil
import sys
import tempfile
from pathlib import Path

DEST = Path("/var/lib/starchaser/greeter")
HOME = Path.home()
THEME = HOME / ".local/state/starchaser/theme.json"
MONITORS = HOME / ".config/hypr/monitors.lua"
COCKPIT = HOME / ".config/starchaser/cockpit.json"
ACCESSIBILITY = HOME / ".config/starchaser/accessibility.json"
# not os.getlogin(): it asks the login records for the terminal's owner and fails with no terminal (a systemd unit,
# CI, `--help` with input from /dev/null)
USER = os.environ.get("USER") or pwd.getpwuid(os.getuid()).pw_name


def put(path: Path, fill) -> None:
    """Write `path` by a temp file of its own in the same folder, moved over it: two accounts syncing at once never
    share one temp name, and a file another account wrote last is replaced, not refused (the folder may be shared
    by the desktop users' group). fill(fh) writes the contents."""
    fd, tmp = tempfile.mkstemp(dir=path.parent, prefix="." + path.name + ".", suffix=".tmp")
    try:
        with os.fdopen(fd, "wb") as fh:
            fill(fh)
        os.chmod(tmp, 0o644)
        os.replace(tmp, path)
    except BaseException:
        try:
            os.unlink(tmp)
        except OSError:
            pass
        raise


def write(path: Path, data: bytes) -> None:
    try:
        if path.read_bytes() == data:
            return
    except OSError:
        pass
    put(path, lambda fh: fh.write(data))


# one value each; the login screen's hyprland.lua accepts exactly these shapes too
FIELDS = {
    "output": re.compile(r"(desc:[^\x00-\x1f\x7f\t\"\\]{1,120}|[A-Za-z0-9-]{1,32})"),
    "mode": re.compile(r"(preferred|highres|highrr|\d{2,5}x\d{2,5}(@\d{1,3}(\.\d{1,3})?)?)"),
    "position": re.compile(r"(auto|-?\d{1,5}x-?\d{1,5})"),
    "scale": re.compile(r"(auto|\d(\.\d{1,16})?)"),
    "transform": re.compile(r"[0-7]"),
    "cm": re.compile(r"(srgb|hdr|wide|edid|hdredid|auto)"),
    "bitdepth": re.compile(r"(8|10)"),
}
COLUMNS = ["kind", "output", "mode", "position", "scale", "transform", "cm", "bitdepth"]


def layout_rows(lua: str) -> list:
    """The monitor rules starchaser displays writes into monitors.lua, read as data (the file is never run):
    ["monitor"|"disabled"|"primary", output, mode, position, scale, transform, cm, bitdepth]. Anything that isn't
    one of those simple values is left out."""
    rows = []
    for block in re.findall(r"hl\.monitor\(\{(.*?)\}\)", lua, re.S):
        vals = {}
        for k, v in re.findall(r"\b(\w+)\s*=\s*(\"[^\"\n]*\"|[\w.-]+)", block):
            v = v[1:-1] if v.startswith('"') else v
            if k in FIELDS and FIELDS[k].fullmatch(v):
                vals[k] = v
            elif k == "disabled" and v == "true":
                vals["disabled"] = "1"
        if "output" not in vals or vals["output"] == "":
            continue
        if vals.get("disabled"):
            rows.append(["disabled", vals["output"]] + [""] * 6)
        elif "mode" in vals:
            rows.append(["monitor"] + [vals.get(c, "") for c in COLUMNS[1:]])
    m = re.search(r"(?m)^-- primary: (.+)$", lua)
    # starchaser displays keeps a screen without a description as "name:<connector>": that one goes by its connector
    if m:
        p = m.group(1).strip()
        out = p[len("name:"):] if p.startswith("name:") else "desc:" + p
        if FIELDS["output"].fullmatch(out):
            rows.append(["primary", out] + [""] * 6)
    return rows


HEX = re.compile(r"#[0-9a-fA-F]{6}")
ROLES = ["bg", "bg_alt", "surface", "surface_hi", "selection", "border", "text", "subtext", "muted", "accent",
         "accent2", "accent3", "success", "warning", "error", "info"]


def _rgb(h: str) -> tuple:
    return tuple(int(h[i:i + 2], 16) / 255 for i in (1, 3, 5))


def _hex(c: tuple) -> str:
    return "#" + "".join("%02x" % max(0, min(255, round(x * 255))) for x in c)


def _lum(c: tuple) -> float:
    lin = [x / 12.92 if x <= 0.03928 else ((x + 0.055) / 1.055) ** 2.4 for x in c]
    return 0.2126 * lin[0] + 0.7152 * lin[1] + 0.0722 * lin[2]


def _contrast(a: tuple, b: tuple) -> float:
    x, y = _lum(a), _lum(b)
    return (max(x, y) + 0.05) / (min(x, y) + 0.05)


def _toward_text(c: str, text: str, backs: list) -> str:
    """Theme.qml's walk: move c toward text in 20 steps until it reads at 4.5:1 on every background."""
    a, t = _rgb(c), _rgb(text)
    for i in range(21):
        k = i / 20
        m = tuple(a[j] + (t[j] - a[j]) * k for j in range(3))
        if all(_contrast(m, b) >= 4.5 for b in backs):
            return _hex(m)
    return text


def login_css(theme: dict) -> str:
    """Mission Control's sign-in page colors: the theme's roles as --mc-* variables, plus hint, accent-text and
    error-text worked out like Theme.qml does. Only #rrggbb values pass; a theme without them gives ""."""
    colors = theme.get("colors") if isinstance(theme, dict) else None
    if not isinstance(colors, dict):
        return ""
    c = {k: colors[k] for k in ROLES if isinstance(colors.get(k), str) and HEX.fullmatch(colors[k])}
    if not all(k in c for k in ("bg", "surface", "surface_hi", "text", "muted", "accent", "error")):
        return ""
    backs = [_rgb(c["bg"]), _rgb(c["surface"]), _rgb(c["surface_hi"])]
    k1 = 0.82 + 0.18 * 0.55
    bg = _rgb(c["bg"])
    dark, light = tuple(x * k1 for x in bg), tuple(x * k1 + (1 - k1) for x in bg)
    derived = {"hint": _toward_text(c["muted"], c["text"], backs),
               "accent-text": _toward_text(c["accent"], c["text"], backs),
               "error-text": _toward_text(c["error"], c["text"], backs + [dark, light])}
    lines = [f"  --mc-{k.replace('_', '-')}: {v.lower()};" for k, v in c.items()]
    lines += [f"  --mc-{k}: {v};" for k, v in derived.items()]
    alpha = ((theme.get("look") or {}) if isinstance(theme.get("look"), dict) else {}).get("popup_alpha")
    if isinstance(alpha, (int, float)) and 0 <= alpha <= 1:
        lines.append(f"  --mc-panel-alpha: {float(alpha):.3f};")
    variant = "light" if theme.get("variant") == "light" else "dark"
    return ("/* Mission Control sign-in colors from the current Starchaser theme (starchaser greeter sync) */\n"
            f":root {{\n  color-scheme: {variant};\n"
            f"  --mcl-logo-dark: {'none' if variant == 'light' else 'inline'};\n"
            f"  --mcl-logo-light: {'inline' if variant == 'light' else 'none'};\n" + "\n".join(lines) + "\n}\n")


def text_scale() -> float:
    """The text size picked in Settings > Accessibility (1, 1.25, 1.5 or 2), else 1. High contrast already reaches
    the login screen in the theme's colors; the text size has to be carried on its own."""
    try:
        scale = json.loads(ACCESSIBILITY.read_text()).get("text_scale")
    except (OSError, ValueError, AttributeError):
        return 1.0
    return float(scale) if type(scale) in (int, float) and scale in (1, 1.25, 1.5, 2) else 1.0


def screen_reader() -> bool:
    """True when the screen reader is on in Settings > Accessibility: the login screen then starts it too."""
    try:
        return json.loads(ACCESSIBILITY.read_text()).get("screen_reader") is True
    except (OSError, ValueError, AttributeError):
        return False


def main() -> int:
    if not DEST.is_dir() or not os.access(DEST, os.W_OK):
        print(f"{DEST} isn't there or isn't writable (the desktop setup creates it)", file=sys.stderr)
        return 1
    keep = set()
    try:
        st = json.loads(THEME.read_text())
    except (OSError, ValueError):
        st = {}
    outs = ((st.get("wallpaper_now") or {}).get("outputs") or {})
    copied = {}
    for out, src in outs.items():
        s = Path(src)
        if not s.is_file():
            continue
        dst = DEST / f"wall-{out}{s.suffix.lower()}"
        if not dst.exists() or dst.stat().st_size != s.stat().st_size or dst.stat().st_mtime < s.stat().st_mtime:
            with open(s, "rb") as src_fh:
                put(dst, lambda fh: shutil.copyfileobj(src_fh, fh))
        copied[out] = str(dst)
        keep.add(dst.name)
    if st:
        st = dict(st)
        st["wallpaper_now"] = dict(st.get("wallpaper_now") or {}, outputs=copied)
        try:
            st["clock24"] = json.loads(COCKPIT.read_text()).get("clock24") is True
        except (OSError, ValueError, AttributeError):
            st["clock24"] = False
        st["text_scale"] = text_scale()
        st["screen_reader"] = screen_reader()
        write(DEST / "theme.json", (json.dumps(st, indent=1) + "\n").encode())
    keep.add("theme.json")
    css = login_css(st) if st else ""
    if css:
        write(DEST / "mc-login.css", css.encode())
    else:
        (DEST / "mc-login.css").unlink(missing_ok=True)   # the sign-in page uses its built-in Starchaser colors
    keep.add("mc-login.css")
    if MONITORS.is_file():
        try:
            rows = layout_rows(MONITORS.read_text(errors="replace"))
        except OSError:
            rows = None
        if rows is not None:
            text = "# Starchaser login screen monitor layout (starchaser greeter sync): " + "\t".join(COLUMNS) + "\n"
            write(DEST / "monitors.tsv", (text + "".join("\t".join(r) + "\n" for r in rows)).encode())
    keep.add("monitors.tsv")
    (DEST / "monitors.lua").unlink(missing_ok=True)      # older versions copied the Lua file itself
    users_f = DEST / "users"
    try:
        users = [u for u in users_f.read_text().split() if u]
    except OSError:
        users = []
    if USER not in users:
        users.append(USER)
    write(users_f, ("\n".join(users) + "\n").encode())
    write(DEST / "last-user", (USER + "\n").encode())
    keep |= {"users", "last-user"}
    for f in DEST.glob("wall-*"):                       # wallpapers for monitors that are gone
        if f.name not in keep:
            f.unlink(missing_ok=True)
    if sys.stdout.isatty():   # a person at a terminal is told; the desktop and scripts see no new output
        print("The login screen now matches your desktop.")
    return 0


if __name__ == "__main__":
    if sys.argv[1:] and sys.argv[1] in ("-h", "--help", "help"):
        # plain words for --help; the file list in the docstring above is for people reading the code
        print("Usage: starchaser greeter sync\n\n"
              "Makes the login screen match your desktop: theme, wallpaper, screen layout, clock and text size.\n"
              "It runs by itself whenever those change, and takes no arguments.\n"
              "On a computer with several people, whoever signed in or changed their look last sets the login screen's look.")
        sys.exit(0)
    if sys.argv[1:]:
        print("starchaser greeter sync: takes no arguments. "
              "Run 'starchaser greeter sync --help' for more help.", file=sys.stderr)
        sys.exit(2)
    sys.exit(main())
