#!/usr/bin/env python3
# summary: Show which apps use the microphone, camera, screen, or location.
"""starchaser privacy: what is using the microphone, the camera, the screen and your location right now.
The cockpit's privacy lights (Spine) follow its event stream; it only reads, never blocks anything.

    starchaser privacy watch      JSON lines on changes; short uses stay visible for six seconds
    starchaser privacy status     JSON: {"mic": [...], "camera": [...], "screen": [...], "location": [...]}
                                  each a list of {"app": name, "pid": n, "start": ticks, "device": "Insta360 Link 2C"}
                                  (or {"app": name, "what": text} for screen); pid 0 or no device when unknown.
                                  start is the process's start time from /proc (for starchaser quit pid PID:START)

    mic       PipeWire recording streams from a real input (an app listening to what the speakers play, like a
              screen recorder capturing system sound, is not the microphone)
    camera    programs that have a camera device (/dev/video*) open
    screen    Starchaser's screen recorder, someone connected to Sunshine (remote desktop), and a screen or window
              shared through the desktop portal (a browser call, a recorder): the portal's PipeWire video stream
              while it runs, named by the app reading it. The taskbar's own window previews don't use the portal,
              so they never show up here.
    location  apps with an active GeoClue client (only when GeoClue is installed: without it nothing can ask)
"""
import ctypes
import json
import os
import re
import select
import shutil
import signal
import struct
import subprocess
import sys
import time
import urllib.request
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
from starchaser_cli import takes_nothing_after


def run(*cmd, timeout=4) -> str:
    if not shutil.which(cmd[0]):
        return ""
    try:
        return subprocess.run(cmd, capture_output=True, text=True, timeout=timeout).stdout
    except subprocess.TimeoutExpired:
        return ""


def proc_start(pid: int) -> int:
    """The process's start time from /proc (clock ticks since boot), 0 when unknown. With the pid it names one exact
    process: the Quit button hands both to starchaser quit, so a pid another program got since is left alone."""
    try:
        stat = Path(f"/proc/{pid}/stat").read_text()
        rest = stat[stat.rfind(")") + 2:].split()
        return int(rest[19]) if len(rest) > 19 and rest[19].isdigit() else 0
    except OSError:
        return 0


def proc_exe(pid: int) -> str:
    """The file name of the program a process runs (/proc/PID/exe), "" when it can't be read."""
    try:
        return Path(os.readlink(f"/proc/{pid}/exe")).name
    except OSError:
        return ""


def proc_label(pid: int) -> str:
    """A readable name for a process: its .desktop-ish name from the command, not 'python3'."""
    try:
        cmd = Path(f"/proc/{pid}/cmdline").read_bytes().split(b"\0")
        exe = Path(cmd[0].decode(errors="replace")).name
        if re.match(r"(python3?|node|bun|electron\d*|java|sh|bash)$", exe):
            for c in cmd[1:]:
                if c == b"-c":                    # inline code: no script name to show
                    break
                if c and not c.startswith(b"-"):
                    return Path(c.decode(errors="replace")).name
            return Path(f"/proc/{pid}/comm").read_text().strip()
        return exe
    except OSError:
        return f"process {pid}"


def own_meter(pid: int) -> bool:
    """The process is Starchaser's own Settings or taskbar: qs (Quickshell) running a config from
    ~/.config/quickshell/settings or .../cockpit, the only two that draw a level meter."""
    if proc_exe(pid) not in ("qs", "quickshell"):
        return False
    try:
        args = [a.decode(errors="replace") for a in Path(f"/proc/{pid}/cmdline").read_bytes().split(b"\0")]
    except OSError:
        return False
    base = str(Path.home() / ".config" / "quickshell")
    return any(a.rstrip("/") in (base + "/settings", base + "/cockpit") for a in args)


def own_noise(pid: int) -> bool:
    """Only the actual noise service may be hidden; a stream's label is untrusted."""
    if proc_exe(pid) != "pipewire":
        return False
    try:
        return any(line.split(":", 2)[-1].rstrip("/").split("/")[-1] == "starchaser-noise.service"
                   for line in Path(f"/proc/{pid}/cgroup").read_text().splitlines())
    except OSError:
        return False


def mic() -> list:
    try:
        outs = json.loads(run("pactl", "-f", "json", "list", "source-outputs") or "[]")
        sources = {s["index"]: s for s in json.loads(run("pactl", "-f", "json", "list", "sources") or "[]")}
    except ValueError:
        return []
    seen, out = set(), []
    for o in outs:
        p = o.get("properties", {})
        src = sources.get(o.get("source")) or {}
        if src.get("name", "").endswith(".monitor"):                     # capturing the speakers, not the mic
            continue
        authed = []
        pid = stream_pid(p, o.get("index"), authed)
        if pid and authed and own_noise(pid):
            continue
        # a volume meter (pavucontrol's peak detect), not a recording: only when the verified process really is
        # pavucontrol; a stream merely named "Peak detect", or claiming pavucontrol's id, still lights the mic
        if (p.get("media.name") == "Peak detect" or p.get("application.id") == "org.PulseAudio.pavucontrol") \
                and pid and proc_exe(pid).startswith("pavucontrol"):
            continue
        # Settings > Sound's own input meter: a "Peak detect" stream from Starchaser's own Settings (or taskbar)
        # process; it lit the mic light while the page was open, and Quit would close Settings. Only with the pid PipeWire
        # checked on the socket (Quickshell is a native client): a PulseAudio app can state the taskbar's pid and
        # binary, and that taskbar is always running, so a stated pid here would hide any recording
        if p.get("media.name") == "Peak detect" and pid and authed and own_meter(pid):
            continue
        app = p.get("application.name") or p.get("application.process.binary") or "An app"
        if app not in seen:
            seen.add(app)
            # which microphone: the device's product name ("Insta360 Link 2C"), else the source's description
            sp = src.get("properties") or {}
            device = sp.get("device.product.name") or src.get("description") or ""
            out.append(label_microphone({"app": app, "pid": pid, "start": proc_start(pid) if pid else 0, "device": device}, ("pulse", o.get("index"))))
    return out


_pw = None


def pw_objects() -> list:
    """pw-dump, read once per status run (the mic and the screen checks both look)."""
    global _pw
    if _pw is None:
        try:
            objs = json.loads(run("pw-dump", timeout=4) or "[]")
        except ValueError:
            objs = []
        _pw = objs if isinstance(objs, list) else []
    return _pw


def stream_pid(p: dict, serial, authed: list = None) -> int:
    """The process behind a recording stream (its properties p), 0 when it can't be trusted.
    A native PipeWire client: pipewire.sec.pid on its client object, the pid PipeWire checked on the socket.
    A PulseAudio client (browsers, Electron apps) reaches PipeWire through pipewire-pulse, so its sec.pid is the
    sound server's own; the only pid there is the one the app states (application.process.id), which another app
    could fill with someone else's pid, so the privacy Quit button would end the wrong app. That one is used only
    when the process really runs the program the stream names (application.process.binary).
    authed, when given, gets True appended when the pid is the one PipeWire checked (not one the app stated)."""
    clients, cid = {}, str(p.get("client.id")) if p.get("client.id") not in (None, "") else None
    for o in pw_objects():
        t, info = o.get("type", ""), o.get("info") or {}
        q = info.get("props") or {}
        if t.endswith(":Client"):
            clients[str(o.get("id"))] = q
        elif cid is None and t.endswith(":Node") and (str(o.get("id")) == str(p.get("object.id")) or str(q.get("object.serial")) == str(serial)):
            cid = str(q.get("client.id")) if q.get("client.id") is not None else None
    c = clients.get(cid) or {}
    try:
        sec = int(c.get("pipewire.sec.pid") or 0)
    except (TypeError, ValueError):
        sec = 0
    pulse = c.get("client.api") == "pipewire-pulse" or p.get("client.api") == "pipewire-pulse"
    if sec and not pulse and (proc_exe(sec) not in ("pipewire", "pipewire-pulse") or own_noise(sec)):
        if authed is not None:
            authed.append(True)
        return sec
    try:
        claimed = int(p.get("application.process.id") or c.get("application.process.id") or 0)
    except (TypeError, ValueError):
        return 0
    binary = p.get("application.process.binary") or c.get("application.process.binary") or ""
    if not claimed or not binary:
        return 0
    try:
        comm = Path(f"/proc/{claimed}/comm").read_text().strip()
    except OSError:
        return 0
    return claimed if binary in (proc_exe(claimed), comm) or binary[:15] == comm else 0


def camera_name(dev: str) -> str:
    """/dev/video0 -> "Insta360 Link 2C" (the driver's name for it, up to its first colon)."""
    try:
        name = Path(f"/sys/class/video4linux/{Path(dev).name}/name").read_text().strip()
    except OSError:
        return ""
    return name.split(":")[0].strip()


def camera_pipewire() -> list:
    nodes, links = {}, []
    for obj in pw_objects():
        info = obj.get("info") or {}
        if obj.get("type", "").endswith(":Node"):
            nodes[obj.get("id")] = info
        elif obj.get("type", "").endswith(":Link") and info.get("state") == "active":
            links.append(info)
    out, seen = [], set()
    for number, info in nodes.items():
        props = info.get("props") or {}
        if props.get("media.class") != "Video/Source" or info.get("state") != "running":
            continue
        camera_source = (props.get("device.api") in ("v4l2", "libcamera") or props.get("api.v4l2.path")
                         or props.get("api.libcamera.path") or "v4l2" in props.get("node.name", "")
                         or "libcamera" in props.get("node.name", ""))
        if not camera_source:
            continue
        reached, pending = set(), [number]
        while pending:
            current = pending.pop()
            for link in links:
                dest = link.get("input-node-id")
                if link.get("output-node-id") == current and dest not in reached:
                    reached.add(dest)
                    pending.append(dest)
        for reader in reached:
            p = (nodes.get(reader) or {}).get("props") or {}
            if not p.get("application.name") and not p.get("media.class", "").startswith("Stream/Input"):
                continue
            pid = stream_pid(p, p.get("object.serial"))
            app = p.get("application.name") or "An app"
            key = (app, number)
            if key not in seen:
                seen.add(key)
                out.append({"app": app, "pid": pid, "start": proc_start(pid) if pid else 0,
                            "device": props.get("node.description") or "Camera"})
        if reached and not any(r[1] == number for r in seen):
            out.append({"app": "An app", "pid": 0, "start": 0, "device": props.get("node.description") or "Camera"})
    return out


def camera() -> list:
    devs = sorted(str(d) for d in Path("/dev").glob("video*"))
    out = camera_pipewire()
    if not devs:
        return out
    seen = {u["app"] for u in out}
    for d in Path("/proc").iterdir():                      # only our own processes are visible to us: that's enough
        if not d.name.isdigit():
            continue
        try:
            for fd in (d / "fd").iterdir():
                dev = os.readlink(fd)
                if dev in devs:
                    name = proc_label(int(d.name))
                    if name not in seen and name not in ("wireplumber", "pipewire"):   # they keep cameras open idle
                        seen.add(name)
                        out.append({"app": name, "pid": int(d.name), "start": proc_start(int(d.name)), "device": camera_name(dev)})
                    break
        except OSError:
            continue
    return out


def portal_shares() -> list:
    """Screens or windows the desktop portal (xdg-desktop-portal-hyprland) is streaming right now: its PipeWire
    Video/Source nodes that are running, named by the app on the other end of the link."""
    nodes, links = {}, []
    for o in pw_objects():
        t, info = o.get("type", ""), o.get("info") or {}
        if t.endswith(":Node"):
            nodes[o.get("id")] = info
        elif t.endswith(":Link"):
            links.append(info)
    out, seen = [], set()
    for nid, info in nodes.items():
        p = info.get("props") or {}
        portal = "xdph" in (p.get("node.name") or "") or "xdg-desktop-portal" in (p.get("application.name") or "") \
            or "xdg-desktop-portal" in (p.get("application.process.binary") or "")
        if p.get("media.class") != "Video/Source" or not portal or info.get("state") != "running":
            continue
        readers = [nodes.get(l.get("input-node-id")) or {} for l in links if l.get("output-node-id") == nid]
        names = [(r.get("props") or {}).get("application.name") or (r.get("props") or {}).get("node.name") for r in readers]
        app = next((n for n in names if n), "An app")
        if app not in seen:
            seen.add(app)
            out.append({"app": app, "what": "sharing the screen"})
    return out


def listening(port: int) -> bool:
    """Something on this computer listens on TCP `port` (read from /proc, so no connection is made)."""
    want = f":{port:04X}"
    for name in ("/proc/net/tcp", "/proc/net/tcp6"):
        try:
            with open(name) as f:
                next(f, None)
                for line in f:
                    parts = line.split()
                    if len(parts) > 3 and parts[3] == "0A" and parts[1].endswith(want):
                        return True
        except OSError:
            continue
    return False


def recorder_screen() -> list:
    out = []
    if run("starchaser", "record", "status").split("\n")[0] == "recording":   # (a second line says how long)
        out.append({"app": "Screen recorder", "what": "recording the screen"})
    return out


def remote_screen() -> list:
    out = []
    # only when something listens there: the cockpit polls this, and a connection attempt every poll with nothing
    # to answer it put a firewall question ('status (python3.14)') in front of people in Ask mode
    if not listening(47989):
        return out
    try:
        with urllib.request.urlopen("http://127.0.0.1:47989/serverinfo", timeout=1) as r:
            if "SUNSHINE_SERVER_BUSY" in r.read().decode(errors="replace"):
                out.append({"app": "Sunshine", "what": "someone is connected to this screen (remote desktop)"})
    except OSError:
        pass
    return out


def screen() -> list:
    return portal_shares() + recorder_screen() + remote_screen()


def location() -> list:
    if not shutil.which("busctl"):
        return []
    tree = run("busctl", "--system", "--list", "tree", "org.freedesktop.GeoClue2")
    out = []
    for path in re.findall(r"/org/freedesktop/GeoClue2/Client/\d+", tree):
        active = run("busctl", "--system", "get-property", "org.freedesktop.GeoClue2", path,
                     "org.freedesktop.GeoClue2.Client", "Active")
        if "true" in active:
            app = run("busctl", "--system", "get-property", "org.freedesktop.GeoClue2", path,
                      "org.freedesktop.GeoClue2.Client", "DesktopId").split('"')[1:2]
            out.append({"app": (app[0] if app else "An app") or "An app"})
    return out


def microphone_pipewire() -> list:
    nodes = {o.get("id"): o.get("info") or {} for o in pw_objects() if o.get("type", "").endswith(":Node")}
    links = [o.get("info") or {} for o in pw_objects() if o.get("type", "").endswith(":Link")]
    out = []
    for number, info in nodes.items():
        props = info.get("props") or {}
        if props.get("media.class") != "Stream/Input/Audio" or info.get("state") != "running":
            continue
        sources = [(nodes.get(l.get("output-node-id")) or {}).get("props") or {} for l in links
                   if l.get("input-node-id") == number and l.get("state") == "active"]
        sources = [p for p in sources if p.get("media.class") == "Audio/Source" and not p.get("node.name", "").endswith(".monitor")]
        if not sources or str(props.get("stream.capture.sink", "false")).lower() == "true":
            continue
        authed = []
        pid = stream_pid(props, props.get("object.serial"), authed)
        if pid and authed and own_noise(pid):
            continue
        if props.get("media.name") == "Peak detect" and pid and (proc_exe(pid).startswith("pavucontrol") or authed and own_meter(pid)):
            continue
        out.append(label_microphone({"app": props.get("application.name") or "An app", "pid": pid,
                    "start": proc_start(pid) if pid else 0, "device": sources[0].get("node.description", "")}, ("pipewire", props.get("object.serial"))))
    return out


def settings_test(pid):
    if not pid or proc_label(pid) != 'pw-record':
        return False
    try:
        parent = int(Path(f'/proc/{pid}/stat').read_text().rsplit(')', 1)[1].split()[1])
        for _ in range(5):
            command = Path(f'/proc/{parent}/cmdline').read_bytes().replace(b'\0', b' ').decode(errors='replace')
            if 'quickshell' in command and 'settings' in command:
                return True
            parent = int(Path(f'/proc/{parent}/stat').read_text().rsplit(')', 1)[1].split()[1])
    except (OSError, ValueError, IndexError):
        pass
    return False


def snapshot() -> dict:
    microphones = mic()
    microphones.extend(u for u in microphone_pipewire() if not any(p["app"] == u["app"] for p in microphones))
    return {"mic": microphones, "camera": camera(), "screen": screen(), "location": location()}


_MIC_TEST_STREAMS = {}


def label_microphone(user, identity, now=None):
    # Closing graph frames may outlive the recorder process. Keep the verified identity for
    # that server-assigned stream only, so its final frame cannot become a new ordinary use.
    now = time.monotonic() if now is None else now
    for key, stamp in list(_MIC_TEST_STREAMS.items()):
        if now - stamp > 30:
            del _MIC_TEST_STREAMS[key]
    test = settings_test(user.get('pid', 0))
    if test and identity[1] is not None:
        _MIC_TEST_STREAMS[identity] = now
    if test or identity in _MIC_TEST_STREAMS:
        return dict(user, app='Settings (microphone test)', test=True)
    return user


def named_observation(current):
    result = {category: [dict(user) for user in users] for category, users in current.items()}
    for user in result.get('mic', []):
        if settings_test(user.get('pid', 0)):
            user.update(app='Settings (microphone test)', test=True)
    return result


def retain_recent(state: dict, current: dict, now: float) -> dict:
    out = {}
    for key in ("mic", "camera", "screen", "location"):
        old = state.setdefault(key, {})
        for user in current.get(key, []):
            identity = (user.get("app"), user.get("pid"), user.get("start"), user.get("device"), user.get("what"))
            old[identity] = (dict(user), now)
        active = {tuple(u.get(k) for k in ("app", "pid", "start", "device", "what")) for u in current.get(key, [])}
        out[key] = []
        for identity, (user, last) in list(old.items()):
            if now - last >= 6 and identity not in active:
                del old[identity]
                continue
            recent = identity not in active
            if recent and any(row['app'] == user['app'] for row in out[key]):
                continue
            if not recent:
                out[key] = [row for row in out[key] if not (row.get('recent') and row['app'] == user['app'])]
            out[key].append(dict(user, recent=recent))
    return out


def merge_objects(objects: dict, updates: list) -> None:
    for obj in updates:
        if not isinstance(obj, dict) or "id" not in obj:
            continue
        number = obj["id"]
        if "info" in obj and obj["info"] is None:
            objects.pop(number, None)
        else:
            old = objects.get(number, {})
            info = dict(old.get("info") or {})
            info.update(obj.get("info") or {})
            objects[number] = {**old, **obj, "info": info}


def camera_events():
    libc = ctypes.CDLL(None, use_errno=True)
    fd = libc.inotify_init1(os.O_NONBLOCK | os.O_CLOEXEC)
    if fd < 0:
        return None
    # Open/close events cover apps accessing a video node directly; creation catches a newly plugged-in camera.
    libc.inotify_add_watch(fd, b"/dev", 0x100 | 0x200)
    for device in Path('/dev').glob('video*'):
        libc.inotify_add_watch(fd, os.fsencode(device), 0x20 | 0x08 | 0x10)
    return os.fdopen(fd, 'rb', buffering=0)


class RecorderEvents:
    """Watch the recorder's runtime PID file and the lifetime of its current process."""
    def __init__(self):
        self.path = Path(os.environ.get("XDG_RUNTIME_DIR") or "/tmp") / "starchaser-record.pid"
        self.process, self.pid = None, None
        libc = ctypes.CDLL(None, use_errno=True)
        fd = libc.inotify_init1(os.O_NONBLOCK | os.O_CLOEXEC)
        if fd < 0:
            raise OSError(ctypes.get_errno(), "Couldn't watch the screen recorder")
        # Watch the directory so deletion/recreation and atomic replacement keep working. Ignore other files:
        # the runtime directory is busy, and the recorder's status itself can restore its missing output file.
        if libc.inotify_add_watch(fd, os.fsencode(self.path.parent), 0x08 | 0x40 | 0x80 | 0x200) < 0:
            error = ctypes.get_errno()
            os.close(fd)
            raise OSError(error, "Couldn't watch the screen recorder")
        self.files = os.fdopen(fd, 'rb', buffering=0)

    def streams(self):
        return [self.files] + ([self.process] if self.process is not None else [])

    def changed(self, stream):
        if stream is self.process:
            self.process.close()
            self.process = None
            return True
        raw, offset, changed = os.read(self.files.fileno(), 65536), 0, False
        while offset + 16 <= len(raw):
            _, mask, _, length = struct.unpack_from('iIII', raw, offset)
            name = raw[offset + 16:offset + 16 + length].split(b'\0', 1)[0]
            changed |= name == os.fsencode(self.path.name) or bool(mask & 0x4000)  # queue overflow
            offset += 16 + length
        return changed

    def update(self):
        try:
            pid = int(self.path.read_text())
        except (OSError, ValueError):
            pid = None
        if pid == self.pid:
            return
        if self.process is not None:
            self.process.close()
            self.process = None
        self.pid = pid
        if pid is not None and pid > 0:
            try:
                self.process = os.fdopen(os.pidfd_open(pid), 'rb', buffering=0)
            except OSError:
                pass  # The recorder may have exited between the snapshot and opening its pidfd.

    def close(self):
        self.files.close()
        if self.process is not None:
            self.process.close()


def recorder_events():
    try:
        return RecorderEvents()
    except OSError:
        return None


def watch() -> None:
    global _pw
    signal.signal(signal.SIGTERM, lambda *_: sys.exit(0))
    # Quickshell can exit without signaling its Process children. Run the same bounded cleanup when its parent
    # dies, and cover a parent exit between reading its PID and installing the kernel's parent-death signal.
    parent = os.getppid()
    ctypes.CDLL(None, use_errno=True).prctl(1, signal.SIGTERM, 0, 0, 0)
    if os.getppid() != parent:
        return
    import runpy
    try:
        permissions = runpy.run_path(str(Path(__file__).resolve().with_name("starchaser-permissions")))
        record_use = permissions["record_use"]
    except (OSError, ImportError, KeyError):
        permissions, record_use = {}, lambda *_: None  # Live indicators remain available during an incomplete upgrade.
    try:
        # A recording that never started must not keep the gray Screen light lit (checked once per sign-in).
        permissions.get("forget_unsaved_recording", lambda: None)()
    except OSError:
        pass  # An unwritable history keeps its entry; live indicators are unaffected.
    state, objects, previous, buffer = {}, {}, "", ""
    pulse_buffer = ""
    current = None
    pulse_users, direct_cameras, recorded, remote = [], [], [], []
    pending = set()
    probe_after = 0
    def observe(current, now):
        current = named_observation(current)
        try:
            record_use(current)
        except (OSError, ValueError):
            pass  # History failure never suppresses a live privacy light.
        return retain_recent(state, current, now)

    # PipeWire's live graph catches brief camera and microphone uses. Other sources refresh only on events or
    # the slow fallback, so an idle desktop no longer launches Python and five commands every two seconds.
    commands = [["pw-dump", "--monitor"], ["pactl", "subscribe"],
                ["dbus-monitor", "--system", "type='signal',sender='org.freedesktop.GeoClue2',interface='org.freedesktop.DBus.Properties'"]]
    children, retry_at = {}, {}
    pw_live = False
    cameras = camera_events()
    recorder = recorder_events()
    try:
        next_check = 0
        while True:
            graph_changed = False
            now = time.monotonic()
            for command in commands:
                name = command[0]
                child = children.get(name)
                if child is not None and child.poll() is not None:
                    if name == "pw-dump":
                        # A short-lived client can leave its last graph in the pipe after exiting. Drain it
                        # before discarding the old generation, so a complete brief capture still lights up.
                        buffer += child.stdout.read().decode(errors="replace")
                        while buffer.strip():
                            buffer = buffer.lstrip()
                            try:
                                updates, end = json.JSONDecoder().raw_decode(buffer)
                            except ValueError:
                                break
                            buffer = buffer[end:]
                            if isinstance(updates, list):
                                merge_objects(objects, updates)
                                _pw = list(objects.values())
                                observe({"mic": microphone_pipewire(), "camera": camera_pipewire(), "screen": portal_shares()}, time.monotonic())
                    child.stdout.close()
                    child.wait()
                    del children[name]
                    retry_at[name] = now + 5
                    if name == "pw-dump":
                        # A new monitor starts with a whole graph. Neither its old objects nor an unfinished
                        # JSON frame may survive a disconnect; fallback reads must also stop using that cache.
                        objects.clear()
                        _MIC_TEST_STREAMS.clear()
                        buffer, _pw, pw_live = "", None, False
                    pending.add("fallback")
                if name not in children and now >= retry_at.get(name, 0) and shutil.which(name):
                    try:
                        children[name] = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
                        retry_at.pop(name, None)
                    except OSError:
                        retry_at[name] = now + 5
            streams = [p.stdout for p in children.values() if p.poll() is None] + ([cameras] if cameras else [])
            if recorder is not None:
                streams += recorder.streams()
            # Wake for real input, a monitor retry, recent-use expiry, or the slow remote-desktop check.
            deadlines = [next_check] + list(retry_at.values())
            if pending:
                deadlines.append(probe_after)
            for users in state.values():
                deadlines.extend(last + 6 for _, last in users.values() if last + 6 > now)
            delay = max(0, min(30, min(deadlines) - now))
            ready = select.select(streams, [], [], delay)[0] if streams else []
            for stream in ready:
                if recorder is not None and stream in recorder.streams():
                    if recorder.changed(stream):
                        pending.add("recorder")
                    continue
                raw = os.read(stream.fileno(), 65536)
                if "pw-dump" in children and stream is children["pw-dump"].stdout:
                    buffer += raw.decode(errors="replace")
                    while buffer.strip():
                        buffer = buffer.lstrip()
                        try:
                            updates, end = json.JSONDecoder().raw_decode(buffer)
                        except ValueError:
                            break
                        buffer = buffer[end:]
                        if isinstance(updates, list):
                            merge_objects(objects, updates)
                            _pw = list(objects.values())
                            pw_live = True
                            # Keep brief uses between frames without starting the external probes for every
                            # frame in a backlog. Reap/restart monitors again after this batch is drained.
                            observe({"mic": microphone_pipewire(), "camera": camera_pipewire(),
                                                  "screen": portal_shares()}, time.monotonic())
                            graph_changed = True
                else:
                    if cameras is not None and stream is cameras:
                        pending.add("camera")
                        cameras.close()
                        cameras = camera_events()
                    elif "pactl" in children and stream is children["pactl"].stdout:
                        pulse_buffer += raw.decode(errors="replace")
                        while "\n" in pulse_buffer:
                            line, pulse_buffer = pulse_buffer.split("\n", 1)
                            # Our list probes create/remove Pulse clients, and pw-dump sees those too.
                            # Only input devices and recording streams can change microphone use.
                            if re.search(r" on (source|source-output) #", line):
                                pending.add("mic")
                    elif raw:
                        pending.add("location")
            now = time.monotonic()
            if current is None or ("fallback" in pending and now >= probe_after):
                if not pw_live:
                    _pw = None
                if recorder is not None:
                    recorder.update()
                current = snapshot()
                pulse_users = [u for u in current["mic"] if u not in microphone_pipewire()]
                direct_cameras = [u for u in current["camera"] if u not in camera_pipewire()]
                recorded = [u for u in current["screen"] if u.get("app") == "Screen recorder"]
                remote = [u for u in current["screen"] if u.get("app") == "Sunshine"]
                pending.clear()
                probe_after = now + 1
                next_check = now + 30
            if pending and now >= probe_after:
                if "mic" in pending:
                    pulse_users = mic()
                if "camera" in pending:
                    direct_cameras = [u for u in camera() if u not in camera_pipewire()]
                if "recorder" in pending:
                    recorded = recorder_screen()
                    if recorder is not None:
                        recorder.update()
                if "location" in pending:
                    current["location"] = location()
                pending.clear()
                probe_after = now + 1
                graph_changed = True
            if now >= next_check:
                remote = remote_screen()  # /proc + HTTP only while Sunshine listens; no audio or recorder probes
                # A disconnected service still has a slow fallback while its monitor reconnects.
                if "pw-dump" not in children or "pactl" not in children:
                    pending.add("fallback")
                next_check = now + 30
                graph_changed = True
            if graph_changed:
                current["mic"] = pulse_users + [u for u in microphone_pipewire() if not any(p["app"] == u["app"] for p in pulse_users)]
                current["camera"] = direct_cameras + camera_pipewire()
                current["screen"] = recorded + remote + portal_shares()
            shown = observe(current, now)
            text = json.dumps(shown)
            if text != previous:
                print(text, flush=True)
                previous = text
            if not streams:
                time.sleep(1)
    finally:
        if recorder is not None:
            recorder.close()
        if cameras:
            cameras.close()
        signal.signal(signal.SIGTERM, signal.SIG_IGN)
        for child in children.values():
            child.terminate()
        for child in children.values():
            try:
                child.wait(timeout=1)
            except subprocess.TimeoutExpired:
                child.kill()
                child.wait(timeout=2)
            child.stdout.close()


def main(argv: list) -> None:
    if argv == ["watch"]:
        watch()
        return
    if (argv[0] if argv else "status") != "status":
        print("starchaser privacy: unknown command: " + " ".join(argv) + "\n"
              "Run 'starchaser privacy --help' for more help.", file=sys.stderr)
        sys.exit(2)
    if len(argv) > 1:
        sys.exit(takes_nothing_after("starchaser privacy", "status", argv))
    print(json.dumps(named_observation(snapshot())))


if __name__ == "__main__":
    if sys.argv[1:2] in (["-h"], ["--help"], ["help"]) \
            or any(a in ("-h", "--help") for a in sys.argv[2:]):      # help after a command word too (r172)
        print(__doc__)
        sys.exit(0)
    main(sys.argv[1:])
