#!/usr/bin/python3 -I
"""Privileged helper for Simple Update.

Runs as root through pkexec (GUI) or sudo (terminal mode) and accepts only
the fixed verbs below, never a command line, so the polkit rule that lets it
run cannot be used to execute anything else. It is installed as a standalone
script and must keep to the standard library.
"""

import os
import shutil
import subprocess
import sys

SAFE_PATH = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"

# Package prompts are hidden behind the progress view: take dpkg's default
# for changed configuration files, and keep the installed one otherwise.
# Wait for the dpkg lock instead of failing while unattended-upgrades or
# PackageKit holds it.
APT_LOCK_WAIT = ["-o", "DPkg::Lock::Timeout=120"]
APT = [
    "apt-get", "-y", *APT_LOCK_WAIT,
    "-o", "Dpkg::Options::=--force-confdef",
    "-o", "Dpkg::Options::=--force-confold",
]
# Machine-readable progress on stdout ("pmstatus:pkg:42.0:Unpacking ...").
APT_PROGRESS = ["-o", "APT::Status-Fd=1"]

VERBS = ("refresh", "upgrade", "dist-upgrade", "autoremove", "clean", "snap-refresh", "reboot",
         "services")

# Mapped files under these paths are what package upgrades replace.
SYSTEM_PATHS = ("/usr/", "/lib", "/bin/", "/sbin/", "/opt/")


class UsageError(Exception):
    pass


def detect_manager(which=None):
    which = which or shutil.which
    if which("apt-get"):
        return "apt"
    if which("pacman"):
        return "pacman"
    raise UsageError("unsupported distribution: no apt-get or pacman found")


def build_command(verb, manager, orphans=(), which=None):
    """The argv for a verb, or None when there is nothing to do."""
    which = which or shutil.which
    if verb == "refresh":
        if manager != "apt":
            # `pacman -Sy` without -u leaves newer databases than installed
            # packages, the partial-upgrade state Arch warns against. Callers
            # use checkupdates, which syncs a private copy, instead.
            raise UsageError("refresh is only available with apt; use checkupdates on Arch")
        return ["apt-get", *APT_LOCK_WAIT, "-o", "APT::Update::Error-Mode=any", "update"]
    if verb == "upgrade":
        if manager == "apt":
            return APT + APT_PROGRESS + ["upgrade"]
        # Always sync and upgrade together: never leave a partial upgrade.
        return ["pacman", "-Syu", "--noconfirm"]
    if verb == "dist-upgrade":
        if manager != "apt":
            raise UsageError("dist-upgrade is only available with apt")
        return APT + APT_PROGRESS + ["dist-upgrade"]
    if verb == "autoremove":
        if manager == "apt":
            return APT + APT_PROGRESS + ["autoremove"]
        return ["pacman", "-Rns", "--noconfirm", *orphans] if orphans else None
    if verb == "clean":
        if manager == "apt":
            return APT + ["autoclean"]
        return ["pacman", "-Sc", "--noconfirm"]
    if verb == "snap-refresh":
        return ["snap", "refresh"]
    if verb == "reboot":
        if which("systemd-run"):
            return ["systemd-run", "--on-active=2", "--quiet",
                    f"--unit=simple-update-reboot-{os.getpid()}", "systemctl", "reboot"]
        return ["shutdown", "-r", "+1"]
    raise UsageError(f"unknown verb: {verb}")


def pacman_orphans():
    # The helper finds the orphans itself rather than taking package names,
    # so a caller can only remove what pacman already considers unneeded.
    result = subprocess.run(["pacman", "-Qdtq"], capture_output=True, text=True)
    return result.stdout.split() if result.returncode == 0 else []


def _maps_deleted_system_file(maps: str) -> bool:
    for line in maps.splitlines():
        if not line.endswith(" (deleted)"):
            continue
        fields = line.split(None, 5)
        if len(fields) == 6 and fields[5].startswith(SYSTEM_PATHS):
            return True
    return False


def _service_unit(cgroup: str) -> str | None:
    """The system service a process belongs to, from /proc/PID/cgroup."""
    for line in cgroup.splitlines():
        path = line.split(":", 2)[-1]
        if not path.startswith("/system.slice/"):
            continue
        for part in path.split("/"):
            if part.endswith(".service"):
                return part
    return None


def stale_services(proc="/proc"):
    """System services still running code from files an upgrade replaced.
    Needs root to read other users' /proc/PID/maps."""
    units = set()
    for entry in os.scandir(proc):
        if not entry.name.isdigit():
            continue
        try:
            with open(os.path.join(entry.path, "maps")) as maps:
                if not _maps_deleted_system_file(maps.read()):
                    continue
            with open(os.path.join(entry.path, "cgroup")) as cgroup:
                unit = _service_unit(cgroup.read())
        except OSError:  # the process exited, or is a kernel thread
            continue
        if unit:
            units.add(unit)
    return sorted(units)


def main(argv=None):
    argv = sys.argv[1:] if argv is None else argv
    if len(argv) != 1 or argv[0] not in VERBS:
        print(f"usage: simple-update-helper {{{'|'.join(VERBS)}}}", file=sys.stderr)
        return 2
    if os.geteuid() != 0:
        print("simple-update-helper must run as root", file=sys.stderr)
        return 2

    os.environ.clear()
    os.environ.update(PATH=SAFE_PATH, DEBIAN_FRONTEND="noninteractive", LC_ALL="C.UTF-8")
    verb = argv[0]
    if verb == "services":
        for unit in stale_services():
            print(unit)
        return 0
    try:
        manager = detect_manager()
        orphans = pacman_orphans() if verb == "autoremove" and manager == "pacman" else ()
        command = build_command(verb, manager, orphans)
    except UsageError as exc:
        print(exc, file=sys.stderr)
        return 2
    if command is None:
        print("Nothing to do.")
        return 0
    sys.stdout.flush()
    try:
        os.execvp(command[0], command)
    except OSError as exc:
        print(f"cannot run {command[0]}: {exc}", file=sys.stderr)
        return 127


if __name__ == "__main__":
    sys.exit(main())
