#!/usr/bin/env python3
"""usage: starchaser-display [--live] [--prefer /dev/dri/cardN] [--text-greeter] -- COMMAND [ARG...]

Starts the compositor (COMMAND: start-hyprland ...) on this computer's graphics, trying each way to a screen in turn
(gpu_select.py) until one shows a picture, and logs every try on stderr. Run by the live stick's console login (the
installer and the live desktop), the sign-in screen (greetd) and the desktop session; a person never needs it.

  --live           the live stick: pick the device wired to the screen first, and as a last try unload NVIDIA's
                   driver (the live user may run modprobe through sudo)
  --prefer DEV     try this device first (Settings > built-in graphics on a hybrid laptop)
  --text-greeter   the sign-in screen: when nothing shows a picture, sign in on the text console instead

A try worked when the compositor's config wrote the file named in STARCHASER_DISPLAY_UP (its hyprland.start hook
lists the screens it found). A compositor that writes nothing in time is asked directly (hyprctl): one that answers
is running with a config from before the hook and stays; one that doesn't is hung, so it is stopped and the next
way is tried. SIGTERM, SIGHUP and SIGINT go on to the compositor and end the tries. Exit: the compositor's own
status after a try worked; 3 when no try did (the caller falls back to text); 128 + the signal when one ended it
during a try.
"""
import json
import os
import shutil
import signal
import subprocess
import sys
import tempfile
import time
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
import gpu_select  # noqa: E402

NO_DISPLAY = 3
# how long a start may take before its config's start hook runs: software rendering on a slow computer is the slow
# case. A compositor still running after this without the hook is asked whether it is up (answering below).
START_WAIT = float(os.environ.get("STARCHASER_DISPLAY_WAIT", "45"))
NVIDIA_ENV = ("LIBVA_DRIVER_NAME", "__GLX_VENDOR_LIBRARY_NAME", "NVD_BACKEND", "__NV_PRIME_RENDER_OFFLOAD",
              "__VK_LAYER_NV_optimus", "GBM_BACKEND")
MESA_EGL = "/usr/share/glvnd/egl_vendor.d/50_mesa.json"
NVIDIA_MODULES = ("nvidia_drm", "nvidia_modeset", "nvidia_uvm", "nvidia", "nouveau")
TEXT_SESSION = "env STARCHASER_TEXT_SIGNIN=1 /usr/local/lib/starchaser/starchaser-session"


def note(text):
    print(f"starchaser-display: {text}", file=sys.stderr, flush=True)


def environment(attempt, base, marker):
    env = dict(base)
    env.pop("AQ_DRM_DEVICES", None)
    if attempt.devices:
        env["AQ_DRM_DEVICES"] = ":".join(attempt.devices)
    env["STARCHASER_DISPLAY_UP"] = str(marker)
    env["STARCHASER_DISPLAY_ATTEMPT"] = attempt.label
    # the desktop's and the installer's configs set NVIDIA's libraries only when this says NVIDIA renders
    env["STARCHASER_DISPLAY_NVIDIA"] = "1" if attempt.nvidia_env else "0"
    if not attempt.nvidia_env:
        for name in NVIDIA_ENV:
            env.pop(name, None)
    if attempt.chosen:
        env["STARCHASER_BUILTIN_GRAPHICS"] = "1"
    else:
        env.pop("STARCHASER_BUILTIN_GRAPHICS", None)
    env.pop("STARCHASER_SAFE_GRAPHICS", None)
    env.pop("LIBGL_ALWAYS_SOFTWARE", None)
    if attempt.software:
        env["STARCHASER_SAFE_GRAPHICS"] = "1"
        env["LIBGL_ALWAYS_SOFTWARE"] = "1"
        if Path(MESA_EGL).is_file():            # NVIDIA's EGL ignores LIBGL_ALWAYS_SOFTWARE: mesa's, which honors it
            env["__EGL_VENDOR_LIBRARY_FILENAMES"] = MESA_EGL
    return env


def stop(proc):
    proc.terminate()
    try:
        proc.wait(10)
    except subprocess.TimeoutExpired:
        proc.kill()
        proc.wait()


def descends(pid, ancestor, proc_root=Path("/proc")):
    """Is process pid the ancestor process or one it started (start-hyprland runs Hyprland as its child)?"""
    for _ in range(32):
        if pid == ancestor:
            return True
        if pid <= 1:
            return False
        try:                            # /proc/PID/stat: "PID (name) state PPID ..."; the name may hold spaces
            pid = int((proc_root / str(pid) / "stat").read_text().rsplit(")", 1)[1].split()[1])
        except (OSError, ValueError, IndexError):
            return False
    return False


def answering(proc, run=subprocess.run, runtime=None, proc_root=Path("/proc")):
    """The start hook never ran. The screens of the Hyprland this try started, if it answers hyprctl (it is running;
    its config has no hook); None when it doesn't answer (hung, or not far enough to listen)."""
    runtime = Path(runtime or os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}")
    for instance in sorted((runtime / "hypr").glob("*/hyprland.lock")):
        try:
            pid = int(instance.read_text().split()[0])
        except (OSError, ValueError, IndexError):
            continue
        if not descends(pid, proc.pid, proc_root):
            continue
        try:
            r = run(["hyprctl", "--instance", instance.parent.name, "-j", "monitors"],
                    capture_output=True, text=True, timeout=5)
            return [str(m.get("name", "")) for m in json.loads(r.stdout)]
        except (OSError, subprocess.SubprocessError, ValueError, AttributeError, TypeError):
            return None
    return None


def unload_nvidia(run=subprocess.run):
    """Live stick only: NVIDIA's driver (or nouveau) out, so the next try runs on the other graphics or the firmware's
    display. Best-effort: a module in use stays, and the try still runs."""
    loaded = [m for m in NVIDIA_MODULES if Path("/sys/module", m).is_dir()]
    if not loaded:
        return
    r = run(["sudo", "-n", "modprobe", "-r", *loaded], capture_output=True, text=True)
    note("unloaded " + " ".join(loaded) if r.returncode == 0 else
         f"couldn't unload {' '.join(loaded)} ({(r.stderr or '').strip() or 'exit ' + str(r.returncode)})")


def read_marker(marker):
    """The start marker's text once it is complete ("up NAME ...\\n"), else None: a file that exists but is empty
    or half written (a config that writes it in place) is not there yet."""
    try:
        text = marker.read_text(errors="replace")
    except OSError:
        return None
    return text if text.startswith("up") and text.endswith("\n") else None


class Display:
    """One run through the tries. Popen and the clock are passed in so tests can play a compositor."""

    def __init__(self, command, attempts, popen=subprocess.Popen, clock=time.monotonic, sleep=time.sleep,
                 unload=unload_nvidia, workdir=None, answering=answering):
        self.command, self.attempts = command, attempts
        self.popen, self.clock, self.sleep, self.unload, self.answering = popen, clock, sleep, unload, answering
        self.workdir = Path(workdir or tempfile.mkdtemp(prefix="starchaser-display-"))
        self.proc = None
        self.tried = []                 # (label, result) for each try, for the caller's one-line reason and tests
        self.stopping = None            # the signal that asked for the end (shutdown, sign-out): no further try

    def forward(self, signum, _frame):
        self.stopping = signum
        if self.proc is not None and self.proc.poll() is None:
            self.proc.send_signal(signum)

    def run(self, base_env):
        total = len(self.attempts)
        for n, attempt in enumerate(self.attempts, 1):
            if self.stopping is not None:
                return self.stopped()
            if attempt.unload_nvidia:
                self.unload()
            marker = self.workdir / f"up-{n}"
            marker.unlink(missing_ok=True)
            env = environment(attempt, base_env, marker)
            note(f"try {n} of {total}: {attempt.label}" +
                 (f" [AQ_DRM_DEVICES={env['AQ_DRM_DEVICES']}]" if attempt.devices else ""))
            start = self.clock()
            self.proc = self.popen(self.command, env=env)
            result = self.watch(attempt, marker, start)
            self.tried.append((attempt.label, result))
            if result == "worked":
                return self.finish()
            if result == "stopped":
                return self.stopped()
        note(f"no way to a screen worked ({total} tried)")
        return NO_DISPLAY

    def stopped(self):
        """A signal asked for the end: the compositor it was passed to goes, and no other way is tried."""
        if self.proc is not None and self.proc.poll() is None:
            try:
                self.proc.wait(10)
            except subprocess.TimeoutExpired:
                stop(self.proc)
        note(f"asked to stop (signal {self.stopping}); no further try")
        return 128 + self.stopping

    def started(self, attempt, screens, rc):
        if attempt.need_screen and not screens and rc is None:
            note("it started but found no screen to show a picture on; next try")
            stop(self.proc)
            return "no screen"
        note("it started" + (": " + ", ".join(screens) if screens else ""))
        return "worked"

    def watch(self, attempt, marker, start):
        while True:
            rc = self.proc.poll()
            if self.stopping is not None:
                return "stopped"
            text = read_marker(marker)
            if text is not None:
                return self.started(attempt, gpu_select.seen_screens(text), rc)
            if rc is not None:
                note(f"it stopped before showing a picture (exit {rc} after {self.clock() - start:.0f} s)")
                return "failed"
            if self.clock() - start > START_WAIT:
                names = self.answering(self.proc)
                if names is None:
                    note(f"no start signal after {START_WAIT:.0f} s and it doesn't answer: stopping it; next try")
                    stop(self.proc)
                    return "hung"
                note(f"no start signal after {START_WAIT:.0f} s, but it answers (a config without the start hook)")
                return self.started(attempt, gpu_select.seen_screens("up " + " ".join(names)), rc)
            self.sleep(0.25)

    def finish(self):
        while True:
            try:
                return self.proc.wait()
            except InterruptedError:
                continue


def text_signin(tried):
    """The sign-in screen found no way to a screen: greetd's text greeter on this console, with the reason."""
    for tty in ("/dev/tty", f"/dev/tty{os.environ.get('XDG_VTNR', '')}"):
        try:
            fd = os.open(tty, os.O_RDWR | os.O_NOCTTY)
            break
        except OSError:
            continue
    else:
        return NO_DISPLAY
    for target in (0, 1, 2):
        os.dup2(fd, target)
    os.write(1, ("\033[H\033[2JStarchaser: the sign-in screen couldn't start on this computer's graphics "
                 f"({len(tried)} ways tried). Sign in here; the boot menu's safe graphics entry may help.\n\n").encode())
    try:
        os.execvp("agreety", ["agreety", "--cmd", TEXT_SESSION])
    except OSError as error:
        note(f"no text sign-in either: {error}")
    return NO_DISPLAY


def main(argv):
    if argv[:1] in (["-h"], ["--help"]):
        print(__doc__.strip())
        return 0
    live = text = False
    prefer = ""
    while argv and argv[0] != "--":
        arg = argv.pop(0)
        if arg == "--live":
            live = True
        elif arg == "--text-greeter":
            text = True
        elif arg == "--prefer" and argv:
            prefer = argv.pop(0)
        else:
            print(__doc__.strip(), file=sys.stderr)
            return 2
    command = argv[1:]
    if not command:
        print(__doc__.strip(), file=sys.stderr)
        return 2
    # drivers that are still loading make devices that aren't there yet: wait for udev (at most 10 s)
    subprocess.run(["udevadm", "settle", "--timeout=10"], capture_output=True)
    cards = gpu_select.scan()
    nvidia = Path("/proc/driver/nvidia/version").is_file()
    note("graphics: " + (", ".join(f"{c.describe()} {c.driver or 'no driver'}"
                                   + (" boot" if c.boot_vga else "")
                                   + (" screens " + "+".join(c.internal + c.external) if c.internal or c.external else "")
                                   for c in cards) or "no graphics device yet"))
    if live and not prefer:
        hint = gpu_select._read(Path("/run/starchaser-primary-gpu"))
        prefer = hint if not gpu_select.choose(cards) else ""
    display = Display(command, gpu_select.attempts(cards, prefer, live=live, nvidia_loaded=nvidia))
    for signum in (signal.SIGTERM, signal.SIGHUP, signal.SIGINT):
        signal.signal(signum, display.forward)
    try:
        status = display.run(os.environ)
    finally:
        shutil.rmtree(display.workdir, ignore_errors=True)
    if status == NO_DISPLAY and text:
        return text_signin(display.tried)
    return status


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
