#!/usr/bin/env python3
"""
edon-wayland-kvm - the remote desktop of a Wayland session, spoken as KVM.

Wayland is the one piece of this module with no upstream at all. MeshCentral's
agent refuses it outright: `getRemoteDesktopStream` checks whether the X server
is Xwayland and, if it is, answers "please modify config to use Xorg" and gives
up (agentcore.c:1372). Under Wayland the compositor does not let anybody read
the screen, so there is nothing for its X11 capture loop to read.

The way in is xdg-desktop-portal, and it changes the shape of the problem in a
way that suits this project: the portal draws its OWN consent dialog, on the
compositor's terms, and no configuration of ours can suppress it. On Wayland the
operating system asks the question we would otherwise have had to ask carefully.

## What this process is

A helper that lives inside the USER's session - not in the root daemon - because
the portal is only reachable on that user's D-Bus. It:

  * opens one combined RemoteDesktop + ScreenCast portal session, which is what
    produces a single dialog rather than two;
  * turns the PipeWire stream the portal hands back into JPEG tiles in
    MeshCentral's KVM wire format, so the viewer already written for the X11 and
    Windows agents draws it without knowing the difference;
  * turns KVM input frames back into portal input calls.

It speaks that protocol over a unix socket, because that is what the agent's
core can wrap in an ordinary duplex stream - the same shape upstream already
uses on macOS.

## Why the portal's classic input methods and not libei

The plan assumed libei, on the strength of upstream documentation. On the stack
actually shipping - xdg-desktop-portal 1.20, GNOME 48, and equally Plasma 6 -
every NotifyPointer*/NotifyKeyboard* method is still present alongside
ConnectToEIS, and the two are mutually exclusive per session. Notify* is plain
D-Bus: no libei linkage, no compiled artefact, no per-architecture build, and
one code path for both halves of the GNOME/KDE matrix. It costs one round trip
per input event, which is worse than libei's shared-memory stream under fast
mouse motion and is the reason to revisit this later - but not the reason to
delay Wayland support by a compiled helper today.
"""

import os
import selectors
import signal
import socket
import struct
import sys
import time

# --- the KVM wire format -------------------------------------------------------

CMD_TILE = 3
CMD_SCREEN = 7
CMD_ALERT = 65
CMD_LONG_ENVELOPE = 27

IN_KEY = 1
IN_MOUSE = 2
IN_COMPRESSION = 5
IN_REFRESH = 6
IN_PAUSE = 8
IN_SET_DISPLAY = 12
IN_ACK = 14
IN_KEY_UNICODE = 85

# Mouse button bits, and the asymmetry that costs a debugging session: on press
# the raw bit arrives, on release it arrives DOUBLED.
BTN_BITS = {0x02: 0x110, 0x08: 0x111, 0x20: 0x112}      # left, right, middle
BTN_RELEASE = {0x04: 0x110, 0x10: 0x111, 0x40: 0x112}


def frame(command, payload=b""):
    """One KVM message. Length counts the four-byte header."""
    length = 4 + len(payload)
    if length <= 0xFFFF:
        return struct.pack(">HH", command, length) + payload
    # The jumbo envelope: `cmd 27, len 8`, then a 24-bit length at bytes 5..7 and
    # the real command at 8..9. Note 24 bits, not 32 - byte 4 is not read.
    return (struct.pack(">HH", CMD_LONG_ENVELOPE, 8)
            + bytes([0, (length >> 16) & 0xFF, (length >> 8) & 0xFF, length & 0xFF])
            + struct.pack(">HH", command, length & 0xFFFF) + payload)


def screen_frame(width, height):
    return frame(CMD_SCREEN, struct.pack(">HH", width, height))


def tile_frame(x, y, jpeg):
    return frame(CMD_TILE, struct.pack(">HH", x, y) + jpeg)


def alert_frame(text):
    return frame(CMD_ALERT, text.encode("utf-8", "replace"))


class Reader:
    """Reassembles input frames out of a byte stream."""

    def __init__(self):
        self.buf = b""

    def push(self, data):
        self.buf += data
        out = []
        while len(self.buf) >= 4:
            command, length = struct.unpack(">HH", self.buf[:4])
            if length < 4 or length > len(self.buf):
                break
            out.append((command, self.buf[4:length]))
            self.buf = self.buf[length:]
        return out


def become(uid):
    """Drops to the console user, completely, and refuses to go on if it cannot.

    The agent can start a child under another uid, but it has no way to change
    the GROUP: its execFile takes a uid and nothing else, and there is no
    setgid anywhere in the binary. That leaves a process running as
    uid 1000 / gid 0, and the portal will not talk to it.

    The reason is worth writing down because the error names none of it. The
    portal identifies its caller by reading /proc/<pid>/root, and that read is
    governed by the same rule as ptrace: the reader has to match the target on
    BOTH uid and gid. A helper with the right uid and the root group is
    therefore refused with

        AccessDenied: Portal operation not allowed: Unable to open /proc/N/root

    So the helper is started as root and drops on its own, which is the one way
    to be sure the group, the supplementary groups and the dumpable flag are all
    right. Refusing rather than continuing matters: a half-dropped helper would
    be a root process holding a session on a user's desktop.
    """
    if uid is None or os.getuid() != 0:
        return ""
    try:
        import pwd
        entry = pwd.getpwuid(uid)
        os.setgid(entry.pw_gid)
        os.initgroups(entry.pw_name, entry.pw_gid)
        os.setuid(uid)
        os.environ.setdefault("HOME", entry.pw_dir)
        os.environ.setdefault("USER", entry.pw_name)
        os.environ.setdefault("LOGNAME", entry.pw_name)
    except Exception as e:
        return f"could not become uid {uid}: {e}"
    if os.getuid() != uid or os.geteuid() != uid:
        return f"could not become uid {uid}"
    return ""


def restore_proc_ownership():
    """Makes /proc/self readable by the user we are now running as.

    The portal identifies its caller by inspecting the calling process, and one
    of the things it opens is /proc/<pid>/root -- that is how it tells a
    sandboxed application from an ordinary one. The agent starts this helper as
    root and drops to the console user's uid, and Linux responds to any uid
    change by clearing the process's "dumpable" flag, which hands /proc/<pid>
    back to root and makes it unreadable by the very user the process is now
    running as.

    The result is a refusal that names nothing recognisable:

        AccessDenied: Portal operation not allowed: Unable to open /proc/N/root

    Setting the flag again is the whole fix. It costs nothing on a helper
    started normally, where the flag was never cleared.
    """
    try:
        import ctypes
        PR_SET_DUMPABLE = 4
        ctypes.CDLL(None, use_errno=True).prctl(PR_SET_DUMPABLE, 1, 0, 0, 0)
    except Exception:
        pass


# --- what the helper needs, and how it says it is missing ----------------------

def probe():
    """Reports what cannot be imported, rather than dying on the first import.

    A helper that exits silently is indistinguishable from a hung tunnel, which
    is the exact failure the Wayland path already had. Whatever is missing is
    said once, in words an operator can act on.
    """
    missing = []
    try:
        import gi                                    # noqa: F401
        gi.require_version("Gio", "2.0")
        gi.require_version("Gst", "1.0")
        from gi.repository import Gio, GLib, Gst     # noqa: F401
    except Exception as e:
        missing.append(f"python3-gi / gir1.2-gst ({e})")
    try:
        import numpy                                 # noqa: F401
    except Exception:
        missing.append("python3-numpy")
    try:
        from PIL import Image                        # noqa: F401
    except Exception:
        missing.append("python3-pil")
    return missing


# --- the portal ----------------------------------------------------------------

class Portal:
    """One combined RemoteDesktop + ScreenCast session.

    Combined deliberately: two separate sessions mean two dialogs, and the
    second one arrives after the operator already believes they are connected.
    The order is fixed - CreateSession, SelectDevices, SelectSources, then
    RemoteDesktop.Start and only that Start. ScreenCast.Start on a combined
    session is an error, and the screencast streams come back in the
    RemoteDesktop response anyway.
    """

    DEST = "org.freedesktop.portal.Desktop"
    PATH = "/org/freedesktop/portal/desktop"

    def __init__(self, log):
        from gi.repository import Gio, GLib
        self.Gio, self.GLib = Gio, GLib
        self.bus = Gio.bus_get_sync(Gio.BusType.SESSION, None)
        self.log = log
        self.session = None
        self.streams = []
        self.devices = 0
        self.restore_token = ""
        self._n = 0

    def _token(self, prefix):
        self._n += 1
        return f"edon{prefix}{os.getpid()}_{self._n}"

    def _prop(self, iface, name):
        try:
            return self.bus.call_sync(self.DEST, self.PATH, "org.freedesktop.DBus.Properties",
                                      "Get", self.GLib.Variant("(ss)", (f"org.freedesktop.portal.{iface}", name)),
                                      self.GLib.VariantType("(v)"), self.Gio.DBusCallFlags.NONE,
                                      5000, None).unpack()[0]
        except Exception:
            return 0

    def _log_code(self, iface, method, code, results):
        # The code goes to the log, never to the operator: 0/1/2 means nothing
        # to the person waiting for a screen, and "refused" with no code means
        # nothing to whoever has to work out why.
        self.log(f"{iface}.{method} -> {code}" + (f" {sorted(results)}" if results else ""))

    def _request(self, iface, method, args, timeout_s):
        """One portal call, waited out on its Request object.

        The Response signal is subscribed BEFORE the call, on the path the
        portal documents as predictable, because the alternative is a race in
        which a fast portal answers before we are listening.
        """
        handle = self._token("h")
        sender = self.bus.get_unique_name()[1:].replace(".", "_")
        req = f"/org/freedesktop/portal/desktop/request/{sender}/{handle}"
        loop = self.GLib.MainLoop()
        result = {"code": 2, "results": {}}

        def on_response(_c, _s, _p, _i, _sig, params):
            code, results = params.unpack()
            result["code"], result["results"] = code, results
            loop.quit()

        sub = self.bus.signal_subscribe(self.DEST, "org.freedesktop.portal.Request", "Response",
                                        req, None, self.Gio.DBusSignalFlags.NONE, on_response)
        options = dict(args[-1])
        options["handle_token"] = self.GLib.Variant("s", handle)
        body = list(args[:-1]) + [options]
        sig = "(" + "".join(t for t in self.SIGNATURES[method]) + ")"

        failed = {}

        def finished(src, res):
            try:
                src.call_finish(res)
            except Exception as e:
                failed["e"] = e
                loop.quit()

        self.bus.call(self.DEST, self.PATH, f"org.freedesktop.portal.{iface}", method,
                      self.GLib.Variant(sig, tuple(body)), None, self.Gio.DBusCallFlags.NONE,
                      -1, None, finished)
        timer = self.GLib.timeout_add_seconds(timeout_s, lambda: (loop.quit(), False)[1])
        loop.run()
        self.GLib.source_remove(timer)
        self.bus.signal_unsubscribe(sub)
        if "e" in failed:
            raise RuntimeError(f"{iface}.{method}: {failed['e']}")
        self._log_code(iface, method, result["code"], result["results"])
        return result["code"], result["results"]

    SIGNATURES = {
        "CreateSession": ["a{sv}"],
        "SelectDevices": ["o", "a{sv}"],
        "SelectSources": ["o", "a{sv}"],
        "Start": ["o", "s", "a{sv}"],
    }

    def open(self, restore_token="", consent_timeout=120):
        """Runs the handshake. Returns "" on success or a reason to show."""
        G = self.GLib
        code, res = self._request("RemoteDesktop", "CreateSession",
                                  [{"session_handle_token": G.Variant("s", self._token("s"))}], 20)
        if code != 0:
            return "the desktop session was refused"
        # Typed 's', not 'o' - an acknowledged upstream bug kept for compatibility.
        self.session = res["session_handle"]

        devices = self._prop("RemoteDesktop", "AvailableDeviceTypes") or 3
        opts = {"types": G.Variant("u", devices & 3)}
        # persist_mode belongs HERE, on SelectDevices. Putting it on
        # SelectSources - which every screencast example does - is answered with
        # "Remote desktop sessions cannot persist" and closes the session.
        opts["persist_mode"] = G.Variant("u", 2)
        if restore_token:
            opts["restore_token"] = G.Variant("s", restore_token)
        code, _ = self._request("RemoteDesktop", "SelectDevices", [self.session, opts], 20)
        if code != 0:
            return "the input devices were refused"

        cursors = self._prop("ScreenCast", "AvailableCursorModes") or 1
        # A cursor mode that is not advertised does not fail, it CLOSES the
        # session. Embedded if it is offered, hidden otherwise.
        cursor = 2 if cursors & 2 else 1
        code, _ = self._request("ScreenCast", "SelectSources", [self.session, {
            "types": G.Variant("u", 1),
            "multiple": G.Variant("b", False),
            "cursor_mode": G.Variant("u", cursor),
        }], 20)
        if code != 0:
            return "the screen source was refused"

        # This is where the portal draws its dialog. The wait is long because a
        # person has to read it; the operator sees "waiting" until they answer.
        code, res = self._request("RemoteDesktop", "Start", [self.session, "", {}], consent_timeout)
        if code == 1:
            return "the person at the computer refused"
        if code != 0:
            return "nobody answered the request on the computer"

        self.devices = res.get("devices", 0)
        self.restore_token = res.get("restore_token", "")
        self.streams = list(res.get("streams", []))
        if not self.streams:
            return "the computer shared no screen"
        return ""

    def pipewire_fd(self):
        v, fds = self.bus.call_with_unix_fd_list_sync(
            self.DEST, self.PATH, "org.freedesktop.portal.ScreenCast", "OpenPipeWireRemote",
            self.GLib.Variant("(oa{sv})", (self.session, {})), self.GLib.VariantType("(h)"),
            self.Gio.DBusCallFlags.NONE, -1, None, None)
        return fds.get(v.unpack()[0])

    def _notify(self, method, sig, args):
        if self.session is None:
            return
        try:
            self.bus.call_sync(self.DEST, self.PATH, "org.freedesktop.portal.RemoteDesktop",
                               method, self.GLib.Variant(sig, args), None,
                               self.Gio.DBusCallFlags.NO_AUTO_START, 2000, None)
        except Exception as e:
            self.log(f"{method}: {e}")

    def pointer_to(self, node, x, y):
        self._notify("NotifyPointerMotionAbsolute", "(oa{sv}udd)",
                     (self.session, {}, node, float(x), float(y)))

    def pointer_button(self, button, pressed):
        # evdev codes, not X11 button numbers and not the browser's 0/1/2.
        self._notify("NotifyPointerButton", "(oa{sv}iu)",
                     (self.session, {}, button, 1 if pressed else 0))

    def pointer_axis(self, dx, dy):
        self._notify("NotifyPointerAxis", "(oa{sv}dd)", (self.session, {}, float(dx), float(dy)))

    def keysym(self, sym, pressed):
        self._notify("NotifyKeyboardKeysym", "(oa{sv}iu)",
                     (self.session, {}, int(sym), 1 if pressed else 0))

    def close(self):
        if self.session is None:
            return
        try:
            self.bus.call_sync(self.DEST, self.session, "org.freedesktop.portal.Session", "Close",
                               None, None, self.Gio.DBusCallFlags.NONE, 2000, None)
        except Exception:
            pass
        self.session = None


# --- capture -------------------------------------------------------------------

TILE = 128
"""Tile edge, in pixels.

The viewer draws a tile wherever it is told, so the size is ours to choose. 128
is upstream's, and it is a reasonable place to sit: smaller means more JPEG
headers and more messages for a typing cursor, larger means resending a great
deal of unchanged screen every time a menu opens.
"""


class Capture:
    """PipeWire frames in, changed JPEG tiles out.

    Only what changed is sent. A desktop is mostly still, so a full frame every
    interval would spend the whole link redrawing a wallpaper; comparing tiles
    against the last frame sent is what makes the difference between a usable
    session and a slideshow.
    """

    def __init__(self, node, fd, log, on_tiles, on_size):
        from gi.repository import Gst
        import numpy as np
        self.Gst, self.np = Gst, np
        self.log, self.on_tiles, self.on_size = log, on_tiles, on_size
        self.previous = None
        self.size = (0, 0)
        self.quality = 70
        self.paused = False
        self.full_redraw = True
        self.min_interval = 0.10
        self.last_at = 0.0
        Gst.init(None)
        # fd is the portal's own PipeWire connection: only this session's nodes
        # are visible on it, which is the point of asking for it at all.
        self.pipeline = Gst.parse_launch(
            f"pipewiresrc fd={fd} path={node} do-timestamp=true keepalive-time=1000 ! "
            f"videoconvert ! video/x-raw,format=RGB ! "
            f"appsink name=out emit-signals=true max-buffers=2 drop=true sync=false")
        self.sink = self.pipeline.get_by_name("out")
        self.sink.connect("new-sample", self._on_sample)

    def start(self):
        self.pipeline.set_state(self.Gst.State.PLAYING)

    def stop(self):
        try:
            self.pipeline.set_state(self.Gst.State.NULL)
        except Exception:
            pass

    def _on_sample(self, sink):
        from gi.repository import Gst
        sample = sink.emit("pull-sample")
        if sample is None:
            return Gst.FlowReturn.OK
        if self.paused:
            return Gst.FlowReturn.OK
        now = time.monotonic()
        if now - self.last_at < self.min_interval:
            return Gst.FlowReturn.OK
        self.last_at = now
        caps = sample.get_caps().get_structure(0)
        w, h = caps.get_value("width"), caps.get_value("height")
        buf = sample.get_buffer()
        ok, info = buf.map(Gst.MapFlags.READ)
        if not ok:
            return Gst.FlowReturn.OK
        try:
            # A row is padded to a stride, so the buffer is usually larger than
            # w*h*3; deriving the stride from the buffer rather than assuming
            # w*3 is what keeps a 1366-wide screen from shearing.
            stride = len(info.data) // h
            frame = self.np.frombuffer(info.data, dtype=self.np.uint8, count=stride * h)
            frame = frame.reshape(h, stride)[:, : w * 3].reshape(h, w, 3)
            self._diff(frame.copy(), w, h)
        finally:
            buf.unmap(info)
        return Gst.FlowReturn.OK

    def _diff(self, frame, w, h):
        from PIL import Image
        import io
        if self.size != (w, h):
            self.size = (w, h)
            self.previous = None
            self.on_size(w, h)
        full = self.full_redraw or self.previous is None
        self.full_redraw = False
        tiles = []
        for y in range(0, h, TILE):
            for x in range(0, w, TILE):
                block = frame[y:y + TILE, x:x + TILE]
                if not full:
                    old = self.previous[y:y + TILE, x:x + TILE]
                    if block.shape == old.shape and not (block != old).any():
                        continue
                out = io.BytesIO()
                Image.fromarray(block, "RGB").save(out, format="JPEG", quality=self.quality)
                tiles.append((x, y, out.getvalue()))
        self.previous = frame
        if tiles:
            self.on_tiles(tiles)


# --- input ---------------------------------------------------------------------

# Browser keyCode -> X11 keysym, for the keys that are not simply their own
# character. Letters and digits already match: keyCode 65..90 is 'A'..'Z' and
# 48..57 is '0'..'9', which are the keysyms too.
KEYSYMS = {
    8: 0xFF08, 9: 0xFF09, 13: 0xFF0D, 16: 0xFFE1, 17: 0xFFE3, 18: 0xFFE9, 19: 0xFF13,
    20: 0xFFE5, 27: 0xFF1B, 32: 0x0020, 33: 0xFF55, 34: 0xFF56, 35: 0xFF57, 36: 0xFF50,
    37: 0xFF51, 38: 0xFF52, 39: 0xFF53, 40: 0xFF54, 45: 0xFF63, 46: 0xFFFF, 91: 0xFFEB,
    92: 0xFFEC, 93: 0xFF67, 96: 0xFFB0, 97: 0xFFB1, 98: 0xFFB2, 99: 0xFFB3, 100: 0xFFB4,
    101: 0xFFB5, 102: 0xFFB6, 103: 0xFFB7, 104: 0xFFB8, 105: 0xFFB9, 106: 0xFFAA,
    107: 0xFFAB, 109: 0xFFAD, 110: 0xFFAE, 111: 0xFFAF, 112: 0xFFBE, 113: 0xFFBF,
    114: 0xFFC0, 115: 0xFFC1, 116: 0xFFC2, 117: 0xFFC3, 118: 0xFFC4, 119: 0xFFC5,
    120: 0xFFC6, 121: 0xFFC7, 122: 0xFFC8, 123: 0xFFC9, 144: 0xFF7F, 145: 0xFF14,
    186: 0x003B, 187: 0x003D, 188: 0x002C, 189: 0x002D, 190: 0x002E, 191: 0x002F,
    192: 0x0060, 219: 0x005B, 220: 0x005C, 221: 0x005D, 222: 0x0027,
}


def keysym_for(key_code):
    if key_code in KEYSYMS:
        return KEYSYMS[key_code]
    if 48 <= key_code <= 57 or 65 <= key_code <= 90:
        return key_code
    return 0


def keysym_for_char(code_point):
    """The Unicode rule: Latin-1 is its own keysym, everything else is offset."""
    if code_point < 0x100:
        return code_point
    return 0x01000000 + code_point


class Session:
    """One viewer, joined to one portal session."""

    def __init__(self, conn, log):
        self.conn = conn
        self.log = log
        self.reader = Reader()
        self.portal = None
        self.capture = None
        self.node = 0
        self.out = b""
        self.held = set()

    # -- outbound ---------------------------------------------------------------

    def send(self, data):
        self.out += data
        self.flush()

    def flush(self):
        while self.out:
            try:
                sent = self.conn.send(self.out)
            except BlockingIOError:
                return
            except OSError:
                self.out = b""
                return
            if sent <= 0:
                return
            self.out = self.out[sent:]

    # -- inbound ----------------------------------------------------------------

    def on_data(self, data):
        for command, payload in self.reader.push(data):
            self.on_frame(command, payload)

    def on_frame(self, command, payload):
        if command == IN_MOUSE:
            self.on_mouse(payload)
        elif command == IN_KEY and len(payload) >= 2:
            self.on_key(payload[0], keysym_for(payload[1]))
        elif command == IN_KEY_UNICODE and len(payload) >= 3:
            self.on_key(payload[0], keysym_for_char(struct.unpack(">H", payload[1:3])[0]))
        elif command == IN_COMPRESSION and len(payload) >= 6 and self.capture:
            # type, level, scaling, frame timer. Only two of them mean anything
            # here: the codec is always JPEG and scaling is the viewer's job.
            self.capture.quality = max(20, min(95, payload[1] or 70))
            interval = struct.unpack(">H", payload[4:6])[0]
            self.capture.min_interval = max(0.03, interval / 1000.0)
        elif command == IN_REFRESH and self.capture:
            self.capture.full_redraw = True
        elif command == IN_PAUSE and self.capture and payload:
            self.capture.paused = payload[0] == 1
            if not self.capture.paused:
                self.capture.full_redraw = True
        elif command in (IN_ACK, IN_SET_DISPLAY):
            pass

    def on_mouse(self, p):
        if len(p) < 6 or self.portal is None:
            return
        button, x, y = p[1], struct.unpack(">H", p[2:4])[0], struct.unpack(">H", p[4:6])[0]
        self.portal.pointer_to(self.node, x, y)
        if len(p) >= 8:
            # A wheel notch rides on the mouse frame, as a signed pair.
            delta = struct.unpack(">h", p[6:8])[0]
            if delta:
                self.portal.pointer_axis(0, -delta / 120.0 * 10.0)
                return
        if button in BTN_BITS:
            self.portal.pointer_button(BTN_BITS[button], True)
            self.held.add(BTN_BITS[button])
        elif button in BTN_RELEASE:
            code = BTN_RELEASE[button]
            self.portal.pointer_button(code, False)
            self.held.discard(code)
        elif button == 0x88:
            for _ in range(2):
                self.portal.pointer_button(0x110, True)
                self.portal.pointer_button(0x110, False)

    def on_key(self, action, sym):
        if sym == 0 or self.portal is None:
            return
        # 0 and 3 are down, 1 and 4 are up; the extended variants matter only to
        # the X11 agent, which used them to pick a scan-code table.
        self.portal.keysym(sym, action in (0, 3))

    def release_all(self):
        """Nothing may be left held when a session ends.

        A button or a modifier still down after the operator disconnects is a
        desktop the person at the machine cannot use - and they have no way to
        know why."""
        if self.portal is None:
            return
        for code in list(self.held):
            self.portal.pointer_button(code, False)
        self.held.clear()
        for sym in (0xFFE1, 0xFFE3, 0xFFE9, 0xFFEB):
            self.portal.keysym(sym, False)


# --- the process ---------------------------------------------------------------

def token_path():
    """Where the portal's restore token is kept, per user.

    In the user's own runtime directory: it is that person's permission, it is
    theirs to revoke by revoking the portal's, and it must not survive them
    logging out on a shared machine. 0600 because it is a permission, not a
    secret worth more than the session it opens.
    """
    base = os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}"
    return os.path.join(base, "edon-devices-portal-token")


def read_token():
    try:
        with open(token_path(), "r", encoding="ascii") as fh:
            return fh.read().strip()
    except OSError:
        return ""


def write_token(token):
    if not token:
        return
    try:
        path = token_path()
        with open(path, "w", encoding="ascii") as fh:
            fh.write(token)
        os.chmod(path, 0o600)
    except OSError:
        pass


def main(argv):
    if "--probe" in argv:
        missing = probe()
        if missing:
            sys.stdout.write("missing: " + ", ".join(missing) + "\n")
            return 3
        sys.stdout.write("ok\n")
        return 0

    if len(argv) < 2:
        sys.stderr.write("usage: edon-wayland-kvm <socket-path> [--consent-timeout=S]\n")
        return 2
    sock_path = argv[1]
    consent_timeout = 120
    uid = None
    for arg in argv[2:]:
        if arg.startswith("--consent-timeout="):
            consent_timeout = max(10, int(arg.split("=", 1)[1]))
        elif arg.startswith("--uid="):
            uid = int(arg.split("=", 1)[1])

    log_path = ""
    for arg in argv[2:]:
        if arg.startswith("--log="):
            log_path = arg.split("=", 1)[1]

    def log(msg):
        line = f"[edon-wayland-kvm] {time.strftime('%H:%M:%S')} {msg}\n"
        sys.stderr.write(line)
        sys.stderr.flush()
        # Also to a file in the user's runtime directory. The agent inherits our
        # stderr and sends it nowhere in particular, and a helper that fails
        # invisibly is the exact shape of the bug this whole module exists to
        # fix. Runtime directory, so it goes when the session does.
        if log_path:
            try:
                with open(log_path, "a", encoding="utf-8") as fh:
                    fh.write(line)
            except OSError:
                pass

    trouble = become(uid)
    if trouble:
        log(trouble)
        serve_error(sock_path, "remote desktop could not start on this computer", log)
        return 6
    # After any uid change Linux clears the dumpable flag, which hands
    # /proc/<pid> back to root -- and the portal reads it. Set it again.
    restore_proc_ownership()

    missing = probe()
    if missing:
        log("missing: " + ", ".join(missing))
        # Said on the wire too: an operator staring at a blank canvas has no
        # other way to learn that a package is absent on the far machine.
        serve_error(sock_path, "remote desktop support is not installed on this computer", log)
        return 3

    from gi.repository import GLib

    try:
        os.unlink(sock_path)
    except OSError:
        pass
    server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    server.bind(sock_path)
    os.chmod(sock_path, 0o600)
    server.listen(1)
    # The agent connects immediately; nothing else ever should.
    server.settimeout(30)
    log(f"in ascolto su {sock_path}")
    try:
        conn, _ = server.accept()
    except socket.timeout:
        log("nessun agent si e' collegato")
        return 4
    finally:
        server.close()
        try:
            os.unlink(sock_path)
        except OSError:
            pass

    conn.setblocking(False)
    session = Session(conn, log)
    loop = GLib.MainLoop()

    portal = Portal(log)
    reason = portal.open(read_token(), consent_timeout)
    if reason:
        log(f"portale: {reason}")
        session.send(alert_frame(reason))
        time.sleep(0.4)
        session.flush()
        conn.close()
        return 5
    write_token(portal.restore_token)
    session.portal = portal
    node = portal.streams[0][0]
    session.node = node
    props = portal.streams[0][1]
    log(f"sessione avviata: nodo {node}, {props.get('size')}, dispositivi {portal.devices}")

    def on_size(w, h):
        session.send(screen_frame(w, h))

    def on_tiles(tiles):
        for x, y, jpeg in tiles:
            session.send(tile_frame(x, y, jpeg))

    capture = Capture(node, portal.pipewire_fd(), log, on_tiles, on_size)
    session.capture = capture
    capture.start()

    def on_readable(fd, condition):
        try:
            data = conn.recv(65536)
        except BlockingIOError:
            return True
        except OSError:
            data = b""
        if not data:
            loop.quit()
            return False
        session.on_data(data)
        return True

    GLib.io_add_watch(conn.fileno(), GLib.PRIORITY_DEFAULT, GLib.IOCondition.IN, on_readable)
    for sig in (signal.SIGTERM, signal.SIGINT):
        GLib.unix_signal_add(GLib.PRIORITY_HIGH, sig, lambda: (loop.quit(), False)[1])

    try:
        loop.run()
    finally:
        session.release_all()
        capture.stop()
        portal.close()
        try:
            conn.close()
        except OSError:
            pass
    log("sessione chiusa")
    return 0


def serve_error(sock_path, message, log):
    """Accepts one connection only to say why there will be no desktop.

    Without this the agent connects to nothing, the tunnel stays open, and the
    operator watches a blank canvas - which is exactly the failure the Wayland
    path had before this helper existed.
    """
    try:
        os.unlink(sock_path)
    except OSError:
        pass
    try:
        server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        server.bind(sock_path)
        os.chmod(sock_path, 0o600)
        server.listen(1)
        server.settimeout(20)
        conn, _ = server.accept()
        conn.sendall(alert_frame(message))
        time.sleep(0.4)
        conn.close()
    except Exception as e:
        log(f"serve_error: {e}")
    finally:
        try:
            server.close()
            os.unlink(sock_path)
        except Exception:
            pass


def guarded(argv):
    """Runs main and makes a crash SAYABLE.

    The agent pipes this process's stderr nowhere in particular, so an
    unhandled exception here used to be perfectly invisible: the tunnel opened,
    the socket closed a moment later, and the operator watched a blank canvas
    with no way to find out why. Whatever kills the helper is written to the
    log the agent passed us, which lives in the user's runtime directory.
    """
    log_path = ""
    for arg in argv[2:]:
        if arg.startswith("--log="):
            log_path = arg.split("=", 1)[1]
    try:
        return main(argv)
    except BaseException:
        import traceback
        text = traceback.format_exc()
        sys.stderr.write(text)
        if log_path:
            try:
                with open(log_path, "a", encoding="utf-8") as fh:
                    fh.write(f"[edon-wayland-kvm] {time.strftime('%H:%M:%S')} EXCEPTION\n{text}")
            except OSError:
                pass
        return 9


if __name__ == "__main__":
    sys.exit(guarded(sys.argv))
