#!/usr/bin/env python3
"""starchaser-admin-software: runs updates and app installs or removals for Settings, so a batch of them in
one sitting asks for the password once.

It checks that the command is one of the four below and runs starchaser-admin with it, unchanged (grant runs nothing).

    starchaser-admin-software update-run <request.json>     update everything (updater.py)
    starchaser-admin-software software-run <request.json>   install or remove an app (software.py)
    starchaser-admin-software pacman-unlock                 clear a lock left by a crash (nothing running holds it)
    starchaser-admin-software grant                         only start the 15 minutes (a removal stopped after the password)
"""
# Why this program exists (decided 2026-10-08; not shown in --help):
# the door Settings > Updates and Settings > Software use for root work, so that a batch
# of updates and installs in one sitting asks for the password once (decided 2026-10-08).
#
# It is its own program so polkit can tell it apart: pkexec picks the polkit action by the program's path, and this
# path has org.starchaser.software. Every other change still goes through starchaser-admin itself
# (the org.starchaser.admin.* actions, auth_admin: the password every time), firewall and security changes included.
#
# How "once per sitting" works. polkit's own memory (auth_admin_keep) belongs to the one program that asked and lasts
# five minutes from the password, so a long update used it up and the next install asked again. Instead, each run
# through this door leaves a grant for the login session it ran in: /run/starchaser/software-grant/<session>-<user>,
# written by root when a password let the run start, and again when an update or install finishes cleanly (a
# failed run, clearing a lock, or a request turned away never renews it). 50-starchaser-software.rules lets org.starchaser.software through without the password while that file is
# younger than GRANT_MINUTES, for that same user in that same session, and only when the session is the active one at
# the computer (local, wheel). A new login session never inherits it (session numbers aren't reused until a restart,
# and /run is emptied at every start).
#
# One password per install queue (decided 2026-11-05: qa/decisions/decisions-2026-11-05.md #2). When the password
# lets in an install the queue in Settings > Software started, the grant also names that queue's helper (its process
# number and start time, written by root; only the installed helper counts, not a program of the user's by its name).
# Until that helper exits (the queue finished or was emptied, or the session ended), the rule lets through runs
# started under it, however long the queue takes; nothing else gets more than the 15 minutes (an install of its own,
# Updates, a later queue), and a run the queue lets in renews nothing.
#
# grant runs nothing: a removal that took the password, then stopped before its run because the app stayed open
# ("Save changes?" canceled), still opens the window that password promised (QA 20261107-0854 005). Like a run, it
# stamps only after a password, so it can never keep a window open by itself.
#
# It runs nothing on its own: it checks that the command is one in ALLOWED and runs starchaser-admin with it (grant aside),
# unchanged (same environment, so PKEXEC_UID still says who asked). Installed root-owned beside starchaser-admin, so
# code the user can edit never runs as root.
import json
import os
import pwd
import re
import subprocess
import sys
import time
from pathlib import Path

ADMIN = os.path.join(os.path.dirname(os.path.realpath(__file__)), "starchaser-admin")
ALLOWED = {"update-run": 2, "software-run": 2, "pacman-unlock": 1, "grant": 1}     # command -> number of words, itself included
GRANTS = Path("/run/starchaser/software-grant")
GRANT_MINUTES = 15                                     # keep in step with 50-starchaser-software.rules (-mmin -15)
HELPER = "/usr/lib/starchaser/bin/starchaser-software"                # the package's link to /usr/share/starchaser/bin/starchaser-software
PROC = Path("/proc")


def grant_file():
    """The grant for the login session this run is in, or None outside one (a user service, ssh without a session):
    then nothing is remembered and the next run asks again. The session must belong to the person who asked."""
    try:
        uid = int(os.environ.get("PKEXEC_UID", "-1"))
        cg = Path("/proc/self/cgroup").read_text()
        name = pwd.getpwuid(uid).pw_name
    except (OSError, ValueError, KeyError):
        return None
    if not re.fullmatch(r"[A-Za-z0-9_.-]+", name):
        return None
    m = re.search(r"/user-(\d+)\.slice/session-([A-Za-z0-9]+)\.scope$", cg.strip().splitlines()[-1] if cg.strip() else "")
    if m:
        return GRANTS / f"{m.group(2)}-{name}" if int(m.group(1)) == uid else None
    # Started outside the session's own cgroup (Settings opened from the update notice's service, from Ask, or from a
    # paired device runs in a unit of the user's service manager). polkit finds no session for such a program, so the
    # rule can't let it through and it asks every time (checked in a qa VM, polkit 127), but the password typed there
    # still opens the window for the person's display session (logind's Display), where the cockpit and Settings
    # opened from it run. A user service with no display session gets nothing remembered.
    if f"/user-{uid}.slice/user@{uid}.service/" not in cg:
        return None
    try:
        sid = subprocess.run(["loginctl", "show-user", str(uid), "-p", "Display", "--value"], capture_output=True,
                             text=True, timeout=5).stdout.strip()
    except (OSError, subprocess.SubprocessError):
        return None
    return GRANTS / f"{sid}-{name}" if re.fullmatch(r"[A-Za-z0-9]+", sid) else None


def fresh(f, pid=None, exe=True) -> bool:
    """Whether the grant is young enough that polkit let this run through without the password (the rule's test)."""
    try:
        st = f.lstat() if f is not None else None
    except OSError:
        return False
    if not st or st.st_uid != 0 or time.time() - st.st_mtime >= GRANT_MINUTES * 60:
        return False
    try:
        mark = f.with_name(f.name + '.settings').read_text().strip()
    except OSError:
        return False
    runner = settings_runner(pid if pid is not None else os.getppid()) if exe else settings_runner(pid, exe=False)
    return bool(mark) and mark == runner


def proc_info(pid: int):
    """(parent, start time, owner) of a running process, or None."""
    try:
        stat = (PROC / str(pid) / "stat").read_text()
        owner = (PROC / str(pid)).stat().st_uid
    except (OSError, ValueError):
        return None
    fields = stat[stat.rfind(")") + 2:].split()       # after "pid (name) ": state, parent, ..., start time (22nd)
    try:
        return int(fields[1]), fields[19], owner
    except (IndexError, ValueError):
        return None


def ancestors(pid: int):
    """pid itself, its parent, and so on up to the first process (a few steps: run, then the queue's helper)."""
    for _ in range(32):
        info = proc_info(pid) if pid > 1 else None
        if info is None:
            return
        yield pid, info
        pid = info[0]


def root_only(path: str) -> bool:
    """Whether path (already resolved) and every folder above it are root's and writable by root alone, so nobody
    else could have put or changed anything there."""
    p = Path(path)
    for q in (p, *p.parents):
        try:
            st = os.stat(q)
        except OSError:
            return False
        if st.st_uid != 0 or st.st_mode & 0o022:
            return False
    return True


def genuine_helper(pid: int, exe: bool = True) -> bool:
    """Whether pid is the installed starchaser software queue-run itself, not a program of the user's that only has
    the name: running exactly "-X utf8 <script> queue-run" (how the helper starts it, and its own first line), the
    script an absolute path that resolves to the installed one, in folders only root can write, and (exe) its program
    a root-owned python. A relative path is turned away: it would be resolved against the process's own folder, which
    it chose."""
    try:
        args = (PROC / str(pid) / "cmdline").read_bytes().split(b"\0")[:-1]
        want = os.path.realpath(HELPER)
    except (OSError, ValueError):
        return False
    if len(args) != 5 or args[1:3] != [b"-X", b"utf8"] or args[4] != b"queue-run" or not args[3].startswith(b"/"):
        return False
    script = os.path.realpath(os.fsdecode(args[3]))
    if script != want or not root_only(script):
        return False
    if not exe:
        return True
    try:
        prog = os.path.realpath(os.readlink(PROC / str(pid) / "exe"))
    except (OSError, ValueError):
        return False
    return re.fullmatch(r"python3(\.\d+)?", os.path.basename(prog)) is not None and root_only(prog)


def settings_runner(pid=None, exe=True):
    """Identify the Settings process in the caller's ancestry, by executable, config, uid and start time.
    The grant records this identity after a password; another Settings instance cannot inherit it."""
    for p, (_, start, owner) in ancestors(pid if pid is not None else os.getppid()):
        try:
            args = (PROC / str(p) / 'cmdline').read_bytes().split(b'\0')[:-1]
            home = pwd.getpwuid(owner).pw_dir
            if (len(args) == 3 and args[1] == b'-p'
                    and os.fsdecode(args[2]) == home + '/.config/quickshell/settings'
                    and Path(os.fsdecode(args[0])).name in ('qs', 'quickshell')):
                # polkitd cannot read another user's /proc/exe. Root checked the executable when recording this
                # exact PID and start time, as for the queue's hold. Root checks it again for its own requests.
                if exe:
                    program = os.path.realpath(os.readlink(PROC / str(p) / 'exe'))
                    if Path(program).name not in ('qs', 'quickshell') or not root_only(program):
                        continue
                return f'{p} {start}'
        except (OSError, ValueError, KeyError):
            continue
    return ''


def queue_runner() -> str:
    """"<pid> <start time>" of the install queue's helper this run was started under (starchaser software queue-run,
    of the person who asked), or "" for any other run."""
    try:
        uid = int(os.environ.get("PKEXEC_UID", "-1"))
    except ValueError:
        return ""
    for pid, (_, start, owner) in ancestors(os.getppid()):
        if owner == uid and genuine_helper(pid):
            return f"{pid} {start}"
    return ""


def queue_mark(f) -> str:
    """The queue helper the grant names, while that same process still runs (a process number used again later has
    another start time), else ""."""
    try:
        st = f.lstat() if f is not None else None
        mark = f.read_text().split() if st and st.st_uid == 0 else []
        info = proc_info(int(mark[0])) if len(mark) == 2 else None
    except (OSError, ValueError):
        return ""
    return " ".join(mark) if info and info[1] == mark[1] else ""


def held(f, pid: int) -> bool:
    """Whether the process pid runs under the queue helper the grant names, so the queue's one password covers it.
    The helper is checked again: the same process (number and start time) could have become another program since.
    Not its program (/proc exe): polkitd, which asks for the rule, may not read another user's, and the door must
    answer as the rule did (or a run the rule let in would renew the grant). Root checked it for this same process
    when the grant named it, and becoming another program replaces the words too."""
    mark = queue_mark(f).split()
    return bool(mark) and any(str(p) == mark[0] and start == mark[1] and genuine_helper(p, exe=False)
                              for p, (_, start, _) in ancestors(pid))


def stamp(f, queue: str = "") -> None:
    if f is None:
        return
    queue = queue or queue_mark(f)                     # a password outside the queue leaves a running queue's mark
    # polkitd's find has to walk into /run/starchaser and the grant folder and see the stamp: with a stricter umask
    # passed along by pkexec they came out 0700 / 0600, polkit found nothing, and the password was asked every time
    mask = os.umask(0o022)
    try:
        GRANTS.mkdir(mode=0o755, parents=True, exist_ok=True)
        os.chmod(GRANTS.parent, 0o755)
        os.chmod(GRANTS, 0o755)
        old = time.time() - 24 * 3600                  # grants of sessions long gone
        for g in GRANTS.iterdir():
            if g != f and g.stat().st_mtime < old:
                g.unlink(missing_ok=True)
        f.touch(mode=0o644)
        os.chmod(f, 0o644)
        f.write_text(queue + "\n" if queue else "")
        settings = settings_runner()
        mark = f.with_name(f.name + '.settings')
        mark.write_text(settings + '\n')
        os.chmod(mark, 0o644)
        now = time.time()
        os.utime(f, (now, now))
    except OSError:
        pass                                           # no grant: the next run asks again, nothing worse
    finally:
        os.umask(mask)


def main(argv: list) -> None:
    cmd = argv[0] if argv else ""
    if cmd in ("-h", "--help", "help") or any(a in ("-h", "--help") for a in argv[1:]):
        print(__doc__.strip())
        return
    if cmd == "commands":                              # read-only, like starchaser-admin's own
        print(json.dumps({"ok": True, "commands": sorted(ALLOWED)}))
        return
    if cmd == "settings-held" and len(argv) == 3:
        if re.fullmatch(r"[A-Za-z0-9]+-[A-Za-z0-9_.-]+", argv[1]) and argv[2].isdigit() and fresh(GRANTS / argv[1], int(argv[2]), exe=False):
            print("held")
        return
    if cmd == "queue-held" and len(argv) == 3:         # read-only: 50-starchaser-software.rules asks this (as polkitd)
        if re.fullmatch(r"[A-Za-z0-9]+-[A-Za-z0-9_.-]+", argv[1]) and argv[2].isdigit() and held(GRANTS / argv[1], int(argv[2])):
            print("held")
        return
    if ALLOWED.get(cmd) != len(argv):
        print(json.dumps({"ok": False, "errors": "starchaser-admin-software only updates, installs and removes software."}))
        sys.exit(2)
    if os.geteuid() != 0:
        print(json.dumps({"ok": False, "errors": "run through pkexec"}))
        sys.exit(1)
    f = grant_file()
    # A run the grant let through must not renew it: otherwise any program in the session could keep the window
    # open forever with runs that do nothing. So the start is stamped only after a password (no fresh grant was
    # there to let this run through), and the end only when that same password's run finished an update or install
    # (the window counts from the end of a long update, not its start). Runs the grant let in leave it as it was,
    # the queue's included: after the queue, the 15 minutes count from its password, as for any other run.
    pw = not fresh(f) and not held(f, os.getppid())
    queue = queue_runner() if pw and cmd == "software-run" else ""
    if pw:
        stamp(f, queue)                                # the password, just now
    if cmd == "grant":
        sys.exit(0)
    rc = subprocess.call([ADMIN] + argv)
    if rc == 0 and pw and cmd != "pacman-unlock":
        stamp(f, queue)
    sys.exit(rc)


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