#!/usr/bin/env python3
# summary: Close a program completely using its process ID.
"""starchaser quit: end a program for real, by its process id (never by name).

An app that hides to the tray (Discord, Vesktop, Claude) keeps running after its window is closed: Super+Q or the
taskbar's Close puts its window away and the app is still there, in the tray and on the microphone. The taskbar's
"Quit <App>", the tray icon's menu and the privacy lights all end it through here.

    starchaser quit pid [--gentle] PID [PID ...]
                                             ask these programs to end; any still running 5 seconds later is ended
                                             for good. PID may be PID:START (the process's start time
                                             from /proc, as starchaser privacy reports it): then only that very
                                             process is touched, never another one that got the number since.
                                             --gentle (the taskbar's Quit, after it asked the app's windows to
                                             close): a program is ended only once it has no window left (it hid to
                                             the tray); one still showing a window 5 seconds later (asking to save,
                                             say) is left to answer, and nothing is sent to it
    starchaser quit tray ID [TITLE]          the same for the program behind a tray icon: the one that put the icon
                                             there (ID and TITLE are the icon's Id and Title, as the tray lists them;
                                             ID may also be the name it registered the icon under). Only when
                                             exactly one registered icon matches: two copies of an app are left alone
    starchaser quit tray-pid ID [TITLE]      only print {"pids": [...]} for that tray icon, ending nothing

Each id is taken up to the program's main process first: the top-most parent that runs the same program file
(the microphone or camera is often held by a helper process of a browser or an Electron app, and ending the helper
alone just restarts it). Interpreters (python, sh, node...) are never walked up through.
Only this user's own processes, never this script, its parent, or process 1. Each ending is aimed at one exact
process, so a number that another program picks up between two steps can't be hit.
"""
import json
import os
import re
import signal
import subprocess
import sys
import time
from pathlib import Path

GRACE = 5.0                                   # seconds between asking (TERM) and ending (KILL); and the gentle wait
INTERPRETERS = {"python", "python3", "sh", "bash", "zsh", "fish", "dash", "node", "bun", "perl", "ruby", "lua"}


def start_time(pid: int):
    """The process's start time (clock ticks since boot) from /proc, or None when it's gone or not ours to read.
    Together with the pid it identifies one process: a reused pid has another start time."""
    try:
        stat = Path(f"/proc/{pid}/stat").read_text()
    except OSError:
        return None
    rest = stat[stat.rfind(")") + 2:].split()      # after "(comm) ": state is field 3, start time field 22
    if not rest or rest[0] == "Z":                 # a zombie: already ended, only waiting to be reaped
        return None
    return int(rest[19]) if len(rest) > 19 and rest[19].isdigit() else None


def parent_of(pid: int) -> int:
    try:
        stat = Path(f"/proc/{pid}/stat").read_text()
        rest = stat[stat.rfind(")") + 2:].split()
        return int(rest[1])
    except (OSError, IndexError, ValueError):
        return 0


def exe_of(pid: int) -> str:
    try:
        return os.readlink(f"/proc/{pid}/exe").split(" (deleted)")[0]
    except OSError:
        return ""


def ours(pid: int) -> bool:
    """Only this user's own processes, and never this script, its parent or init."""
    if pid <= 1 or pid in (os.getpid(), os.getppid()):
        return False
    try:
        return os.stat(f"/proc/{pid}").st_uid == os.getuid()
    except OSError:
        return False


def main_process(pid: int) -> int:
    """The top-most parent of pid that runs the same program file (an Electron app's audio helper -> the app)."""
    exe = exe_of(pid)
    if not exe or Path(exe).name.rstrip("0123456789.") in INTERPRETERS or Path(exe).name in INTERPRETERS:
        return pid
    seen = {pid}
    while True:
        pp = parent_of(pid)
        if pp <= 1 or pp in seen or not ours(pp) or exe_of(pp) != exe:
            return pid
        seen.add(pp)
        pid = pp


def note_ended(targets: dict) -> None:
    """One line for the person at a terminal; Settings and the taskbar, which check the result themselves, see
    nothing on a pipe."""
    if not targets or not sys.stdout.isatty():
        return
    rows = sorted(targets)
    if len(rows) == 1:
        t = targets[rows[0]]
        print(f"Ended process {t.pid}" + (f" ({t.name})" if t.name else "") + ".")
    else:
        print(f"Ended {len(rows)} processes.")


class Target:
    """One exact process: its pid, the start time it had when found, and a pidfd to signal it (not the number)."""

    def __init__(self, pid: int, start: int):
        self.pid, self.start, self.fd = pid, start, None
        try:
            self.name = Path(f"/proc/{pid}/comm").read_text().strip()
        except OSError:
            self.name = ""
        try:
            self.fd = os.pidfd_open(pid)
        except (AttributeError, OSError):
            self.fd = None                         # no pidfd here: os.kill, guarded by the start-time check

    def alive(self) -> bool:
        return start_time(self.pid) == self.start

    def send(self, sig: int) -> None:
        if not self.alive():
            return
        try:
            if self.fd is not None:
                signal.pidfd_send_signal(self.fd, sig)
            else:
                os.kill(self.pid, sig)
        except OSError:
            pass


def window_pids() -> set:
    """The processes that have a window right now (Hyprland's list); empty when there's no Hyprland to ask."""
    try:
        r = subprocess.run(["hyprctl", "-j", "clients"], capture_output=True, text=True, timeout=3)
        return {int(c.get("pid") or 0) for c in json.loads(r.stdout)} if r.returncode == 0 else set()
    except (OSError, subprocess.TimeoutExpired, ValueError, TypeError):
        return set()


def end(pids: list, gentle: bool = False) -> int:
    """TERM each, then KILL whatever is still the same process after GRACE seconds. Returns 0 when something was asked.
    pids: ints, or (pid, start) pairs for a pid that must still be the process it was when it was looked up."""
    targets = {}
    for pid in pids:
        pid, want = pid if isinstance(pid, tuple) else (pid, None)
        if want is not None and start_time(pid) != want:
            print(f"starchaser quit: process {pid} is not the one it was; left alone", file=sys.stderr)
            continue
        pid = main_process(pid)
        if not ours(pid):
            continue
        st = start_time(pid)
        if st is not None and pid not in targets:
            targets[pid] = Target(pid, st)
    if not targets:
        print("starchaser quit: nothing to end (not running, or not this user's program)", file=sys.stderr)
        return 1
    if gentle:
        # the windows were asked to close: a program that ends by itself is done; one with no window left hid to
        # the tray and is ended; one still showing a window after the wait is answering something, and is left alone
        deadline = time.monotonic() + GRACE
        while True:
            live = {p for p, t in targets.items() if t.alive()}
            if not live:
                note_ended(targets)
                return 0
            showing = live & window_pids()
            if not showing or time.monotonic() >= deadline:
                break
            time.sleep(0.3)
        for p in showing:
            print(f"starchaser quit: process {p} still has a window open; left alone", file=sys.stderr)
        targets = {p: t for p, t in targets.items() if p in live - showing}
        if not targets:
            note_ended(targets)
            return 0
    for t in targets.values():
        t.send(signal.SIGTERM)
    deadline = time.monotonic() + GRACE
    while time.monotonic() < deadline:
        if not any(t.alive() for t in targets.values()):
            break                                  # all gone
        time.sleep(0.2)
    for t in targets.values():
        t.send(signal.SIGKILL)                     # only the very same process (Target.alive)
    note_ended(targets)
    return 0


def busctl(*args) -> dict:
    try:
        r = subprocess.run(["busctl", "--user", "--json=short", *args], capture_output=True, text=True, timeout=4)
        return json.loads(r.stdout) if r.returncode == 0 and r.stdout.strip() else {}
    except (OSError, subprocess.TimeoutExpired, ValueError):
        return {}


def tray_pids(ident: str, title: str) -> list:
    """The process behind the tray icon with this Id (or bus name), through the StatusNotifierWatcher's list and
    the D-Bus daemon's owner lookup. The icon the cockpit shows is known by its Id and Title only (not its bus
    name), so when two registered icons match (two copies of one app) neither can be told to be the one clicked:
    an empty list, and nothing is ended."""
    reg = busctl("get-property", "org.kde.StatusNotifierWatcher", "/StatusNotifierWatcher",
                 "org.kde.StatusNotifierWatcher", "RegisteredStatusNotifierItems").get("data") or []
    owners = []
    for entry in reg:
        bus, _, path = str(entry).partition("/")
        path = "/" + path if path else "/StatusNotifierItem"
        if not bus:
            continue
        if ident not in (bus, entry):
            got = busctl("get-property", bus, path, "org.kde.StatusNotifierItem", "Id").get("data")
            if got != ident:
                continue
            if title:
                t = busctl("get-property", bus, path, "org.kde.StatusNotifierItem", "Title").get("data")
                if t and t != title:
                    continue
        owner = busctl("call", "org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus",
                       "GetConnectionUnixProcessID", "s", bus).get("data") or []
        if owner and isinstance(owner[0], int) and owner[0] > 1:
            owners.append(owner[0])
    if len(set(owners)) > 1:
        print(f"starchaser quit: {len(set(owners))} running copies register a tray icon as {ident!r}; "
              "quit the one you mean from its own window", file=sys.stderr)
        return []
    return sorted(set(owners))


def main(argv: list) -> int:
    cmd = argv[0] if argv else ""
    if cmd in ("-h", "--help", "help") or any(x in ("-h", "--help") for x in argv[1:]):
        print(__doc__.strip())
        return 0
    if cmd == "pid":
        gentle = "--gentle" in argv[1:]
        ids = [a for a in argv[1:] if a != "--gentle"]
        if ids and all(re.fullmatch(r"\d+(:\d+)?", a) for a in ids):
            return end([(int(a.split(":")[0]), int(a.split(":")[1])) if ":" in a else int(a) for a in ids], gentle)
    if cmd in ("tray", "tray-pid") and len(argv) in (2, 3):
        pids = [main_process(p) for p in tray_pids(argv[1], argv[2] if len(argv) == 3 else "")]
        pids = sorted({p for p in pids if ours(p)})
        if cmd == "tray-pid":
            print(json.dumps({"pids": pids}))
            return 0
        if not pids:
            print(f"starchaser quit: no one tray icon registered as {argv[1]!r}", file=sys.stderr)
            return 1
        return end(pids)
    usage = {"pid": "pid [--gentle] PID [PID ...]   (PID: a number, or PID:START)",
             "tray": "tray ID [TITLE]", "tray-pid": "tray-pid ID [TITLE]"}
    if cmd in usage:
        print(f"starchaser quit: wrong arguments for '{cmd}'. Usage: starchaser quit {usage[cmd]}\n"
              "Run 'starchaser quit --help' for more help.", file=sys.stderr)
    elif not cmd:
        print("starchaser quit: no command given. Run 'starchaser quit --help' for more help.", file=sys.stderr)
    else:
        print(f"starchaser quit: unknown command {cmd!r}. Run 'starchaser quit --help' for more help.", file=sys.stderr)
    return 2


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