#!/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. The one verb that takes
arguments, restart-services, acts only on units the helper itself finds
running replaced code. It is installed as a standalone script and must keep
to the standard library.
"""

import fnmatch
import io
import json
import os
import re
import shutil
import signal
import subprocess
import sys
import syslog
import time
from collections.abc import Callable, Iterable, Sequence
from typing import IO, Any, cast

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", "restart-services", "repair")
# The only verb that takes arguments: the units to restart.
RESTART_SERVICES = "restart-services"

# Verbs that run a package manager transaction. Losing the caller (window
# killed, logout, Ctrl-C) must not stop one halfway, so the helper runs them
# under supervision instead of exec'ing the package manager.
SUPERVISED = ("upgrade", "dist-upgrade", "autoremove", "repair")

# Present while a supervised verb runs. One left behind by a dead helper
# tells the app that the last update was interrupted. Readable by users.
RUN_MARKER = "/var/lib/simple-update/running.json"
BOOT_ID = "/proc/sys/kernel/random/boot_id"
# Where the package manager's output goes once the caller has gone away.
JOURNAL_ID = "simple-update-helper"

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

# Never starting with "-", so systemctl can't take one for an option.
SERVICE_UNIT = re.compile(r"\w[\w@.:-]*\.service")
# Services that restarting would end the desktop session, log users out or
# break the authentication the app runs under. They are reported, but only a
# reboot restarts them.
KEEP_RUNNING = (
    "dbus.service", "dbus-broker.service", "systemd-logind.service", "elogind.service",
    "polkit.service", "display-manager.service", "gdm.service", "gdm3.service", "sddm.service",
    "lightdm.service", "lxdm.service", "xdm.service", "slim.service", "greetd.service", "ly.service",
    "getty@*.service", "serial-getty@*.service", "autovt@*.service", "container-getty@*.service",
    "console-getty.service", "user@*.service", "emergency.service", "rescue.service",
)
# How long one restart may take: systemd's default stop and start timeouts
# are 90 seconds each.
RESTART_TIMEOUT = 300

PACMAN_CACHE = "/var/cache/pacman/pkg/"
PACMAN_DBPATH = "/var/lib/pacman/"
# libalpm's lock, in the database directory.
PACMAN_LOCK = "db.lck"
# pacman 7 downloads into one of these inside the cache directory.
PACMAN_DOWNLOAD_DIR = re.compile(r"download-\w{6}")


class UsageError(Exception):
    pass


def os_release_values(text: str) -> dict[str, str]:
    values = {}
    for line in text.splitlines():
        key, sep, value = line.partition("=")
        if sep:
            values[key.strip()] = value.strip().strip("\"'")
    return values


def is_arch_based(os_release: str) -> bool:
    """Arch Linux or a derivative (Manjaro, EndeavourOS, ...)."""
    values = os_release_values(os_release)
    return "arch" in [values.get("ID", ""), *values.get("ID_LIKE", "").split()]


def detect_manager(which: Callable[[str], str | None] | None = None,
                   os_release: str | os.PathLike[str] = "/etc/os-release") -> str:
    which = which or shutil.which
    # Arch packages apt and Debian packages pacman, so when both are
    # installed the distribution decides.
    try:
        with open(os_release) as f:
            arch = is_arch_based(f.read())
    except OSError:
        arch = False
    for manager, binary in ((("pacman", "pacman"), ("apt", "apt-get")) if arch
                            else (("apt", "apt-get"), ("pacman", "pacman"))):
        if which(binary):
            return manager
    raise UsageError("unsupported distribution: no apt-get or pacman found")


def build_command(verb: str, manager: str, orphans: Sequence[str] = (),
                  which: Callable[[str], str | None] | None = None) -> list[str] | 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 == "repair":
        if manager == "apt":
            # Finish configuring what an interrupted dpkg unpacked; main()
            # follows with `apt-get -f install` for broken dependencies.
            return ["dpkg", "--force-confdef", "--force-confold", "--configure", "-a"]
        # A full upgrade finishes an interrupted one on Arch.
        return ["pacman", "-Syu", "--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}")


class Output:
    """Where the helper's and the package manager's output goes: the
    caller's pipe while it is there, then the system journal. A package
    manager writing into a closed pipe gets SIGPIPE or EPIPE, which can stop
    it, or a maintainer script, halfway."""

    def __init__(self, stream: IO[bytes] | None = None):
        self.stream = stream
        self.detached = False
        self.pending = b""

    def write(self, data: bytes) -> None:
        if not self.detached:
            try:
                stream = self.stream or sys.stdout.buffer
                stream.write(data)
                stream.flush()
                return
            except (OSError, ValueError):  # ValueError: the stream was closed
                self.detached = True
                if self.stream is None:
                    # So that flushing stdout at exit can't fail either.
                    os.dup2(os.open(os.devnull, os.O_WRONLY), 1)
                syslog.openlog(JOURNAL_ID, syslog.LOG_PID, syslog.LOG_USER)
                syslog.syslog(syslog.LOG_WARNING, "lost the connection to Simple Update; "
                              "the update continues and its output is logged here")
        self.pending += data
        *lines, self.pending = re.split(rb"\r\n|\r|\n", self.pending)
        for line in lines:
            # Skip apt's machine-readable progress lines.
            if line.strip() and not re.match(rb"(dl|pm)status:", line):
                syslog.syslog(syslog.LOG_INFO, line.decode("utf-8", "replace"))

    def say(self, text: str) -> None:
        self.write(text.encode() + b"\n")


OUT = Output()


def say(text: str) -> None:
    OUT.say(text)


def systemd_running() -> bool:
    return os.path.isdir("/run/systemd/system")


def logind_running() -> bool:
    # Without logind (some containers) systemd-inhibit fails, and would
    # take the command with it.
    return os.path.isdir("/run/systemd/seats")


def leave_session(verb: str, run: Callable[..., Any] = subprocess.run) -> None:
    """Move the helper out of the caller's login session into a scope of its
    own, so that logging out doesn't kill it with the session's processes
    (logind's KillUserProcesses=yes). Best effort: without systemd, or if
    this fails, the helper stays where it is."""
    if not systemd_running() or not shutil.which("busctl"):
        return
    pid = str(os.getpid())
    run(["busctl", "call", "org.freedesktop.systemd1", "/org/freedesktop/systemd1",
         "org.freedesktop.systemd1.Manager", "StartTransientUnit", "ssa(sv)a(sa(sv))",
         f"simple-update-{verb}-{pid}.scope", "fail", "3",
         "Description", "s", f"Simple Update ({verb})",
         "PIDs", "au", "1", pid,
         "CollectMode", "s", "inactive-or-failed", "0"],
        stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)


def ignore_hangups() -> None:
    """Outlive the caller. A no-op handler rather than SIG_IGN: handlers are
    reset on exec, so the package manager keeps its default signal handling
    (it runs in a session of its own, so a terminal's Ctrl-C or hangup never
    reaches it)."""
    for signum in (signal.SIGHUP, signal.SIGINT, signal.SIGTERM, signal.SIGQUIT):
        signal.signal(signum, lambda *_: None)


def inhibited(argv: list[str]) -> list[str]:
    """argv, holding off suspend and shutdown while it runs."""
    if not logind_running() or not shutil.which("systemd-inhibit"):
        return argv
    return ["systemd-inhibit", "--what=sleep:shutdown", "--mode=block", "--who=Simple Update",
            "--why=Installing updates", *argv]


def supervise(argv: list[str]) -> int:
    """Run argv to completion, relaying its output, and return its status.
    It runs in a new session, so it gets none of the signals meant for the
    caller, and keeps running if the caller goes away."""
    try:
        proc = subprocess.Popen(inhibited(argv), stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
                                stderr=subprocess.STDOUT, start_new_session=True)
    except OSError as exc:
        say(f"cannot run {argv[0]}: {exc.strerror or exc}")
        return 127
    # A PIPE opened with the default buffering is a BufferedReader.
    stdout = cast(io.BufferedReader, proc.stdout)
    while chunk := stdout.read1(65536):
        OUT.write(chunk)
    stdout.close()
    return proc.wait()


def boot_id(path: str = BOOT_ID) -> str:
    try:
        with open(path) as f:
            return f.read().strip()
    except OSError:
        return ""


def process_start_time(pid: object, proc: str = "/proc") -> int | None:
    """When a process started, in clock ticks since boot (field 22 of
    /proc/PID/stat), or None when it doesn't exist. With the PID, it tells
    a process apart from a later one that reuses the PID."""
    try:
        with open(os.path.join(proc, str(pid), "stat")) as f:
            stat = f.read()
    except OSError:
        return None
    # The command name in parentheses may contain spaces; field 3 follows it.
    fields = stat[stat.rfind(")") + 2:].split()
    try:
        return int(fields[19])
    except (IndexError, ValueError):
        return None


def mark_running(verb: str, path: str = RUN_MARKER) -> None:
    """Record the run so the next start can tell when it never finished."""
    os.makedirs(os.path.dirname(path), mode=0o755, exist_ok=True)
    record = {"verb": verb, "pid": os.getpid(), "start_time": process_start_time(os.getpid()),
              "boot_id": boot_id(), "started": int(time.time())}
    temporary = f"{path}.{os.getpid()}"
    fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o644)
    with os.fdopen(fd, "w") as f:
        json.dump(record, f)
    os.replace(temporary, path)


def clear_marker(path: str = RUN_MARKER) -> None:
    try:
        os.unlink(path)
    except FileNotFoundError:
        pass


def pacman_orphans() -> list[str]:
    # 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 pacman_conf(key: str, default: str) -> list[str]:
    """The values of a pacman.conf option, or [default] when unset."""
    try:
        result = subprocess.run(["pacman-conf", key], capture_output=True, text=True)
    except OSError:
        return [default]
    values = [line for line in result.stdout.splitlines() if line.strip()]
    return values if result.returncode == 0 and values else [default]


def pacman_dbpath() -> str:
    return pacman_conf("DBPath", PACMAN_DBPATH)[0]


def lock_is_held(lock: str, proc: str = "/proc") -> bool:
    """Whether any process has the lock file open. libalpm keeps it open for
    as long as it holds the lock, so a lock nobody has open was left behind
    by a crashed or killed run. Needs root to read other users' fds."""
    target = os.path.realpath(lock)
    for entry in os.scandir(proc):
        if not entry.name.isdigit():
            continue
        try:
            fds = list(os.scandir(os.path.join(entry.path, "fd")))
        except OSError:  # the process exited
            continue
        for fd in fds:
            try:
                if os.readlink(fd.path) == target:
                    return True
            except OSError:
                continue
    return False


def clear_stale_lock(dbpath: str, proc: str = "/proc") -> None:
    """Remove pacman's lock when no running process holds it. Otherwise
    every update fails with "unable to lock database" until it is removed
    by hand. A lock still held is left alone."""
    lock = os.path.join(dbpath, PACMAN_LOCK)
    if not os.path.exists(lock) or lock_is_held(lock, proc):
        return
    try:
        os.unlink(lock)
    except FileNotFoundError:  # released meanwhile
        return
    say(f"Removed a stale pacman lock ({lock}) left by an interrupted run.")


def pacman_keyrings() -> list[str]:
    """Installed pacman keyring packages (archlinux-keyring and those of
    derivatives): the packages owning the keyring directory."""
    result = subprocess.run(["pacman", "-Qqo", "/usr/share/pacman/keyrings/"],
                            capture_output=True, text=True)
    return result.stdout.split() if result.returncode == 0 else []


def upgrade_keyrings(keyrings: Sequence[str]) -> int:
    """Sync, then upgrade outdated keyrings before everything else, as the
    Arch wiki advises: on a system not updated for a while, packages signed
    by new keys fail to verify until the keyring that knows them is
    installed. Keyrings in IgnorePkg are left alone. The caller must follow
    with `pacman -Su`, since the databases are now synced."""
    status = supervise(["pacman", "-Sy", "--noconfirm"])
    if status != 0:
        return status
    # `pacman -Qu` exits 1 when nothing is upgradable.
    upgradable = subprocess.run(["pacman", "-Qu"], capture_output=True, text=True).stdout
    outdated = [line.split()[0] for line in upgradable.splitlines()
                if line.split() and line.split()[0] in keyrings and "[ignored]" not in line]
    if not outdated:
        return 0
    say(f"Upgrading {', '.join(outdated)} first.")
    return supervise(["pacman", "-S", "--needed", "--noconfirm", *outdated])


def remove_partial_downloads(cachedirs: Iterable[str], dbpath: str) -> None:
    """Delete what interrupted downloads left in the package cache: `*.part`
    files and pacman 7's `download-XXXXXX` directories. `pacman -Sc` can't
    load them as packages, so it reports "could not open file" for each one
    and keeps them forever. pacman's lock is held meanwhile, so a download
    in progress is never touched."""
    lock = os.path.join(dbpath, PACMAN_LOCK)
    try:
        lock_fd = os.open(lock, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o000)
    except OSError as exc:
        say(f"Leaving partial downloads in place: cannot lock {lock}: {exc.strerror}")
        return
    try:
        for cachedir in cachedirs:
            try:
                entries = list(os.scandir(cachedir))
            except OSError:
                continue
            for entry in entries:
                try:
                    if PACMAN_DOWNLOAD_DIR.fullmatch(entry.name) and entry.is_dir(follow_symlinks=False):
                        shutil.rmtree(entry.path)
                    elif entry.name.endswith(".part") and entry.is_file(follow_symlinks=False):
                        os.unlink(entry.path)
                    else:
                        continue
                except OSError as exc:
                    say(f"could not remove {entry.path}: {exc.strerror}")
                    continue
                say(f"removed {entry.path}")
    finally:
        os.close(lock_fd)
        os.unlink(lock)


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: str = "/proc") -> list[str]:
    """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 restartable(unit: str) -> bool:
    """Whether a service may be restarted without a reboot."""
    return not any(fnmatch.fnmatchcase(unit, pattern) for pattern in KEEP_RUNNING)


def restart_services(units: Sequence[str], proc: str = "/proc",
                     run: Callable[..., subprocess.CompletedProcess[str]] = subprocess.run) -> int:
    """Restart the named services one at a time, printing one line for each:
    "restarted UNIT", "failed UNIT: why", or "current UNIT" when it no
    longer runs replaced code and was left alone. Only services that still
    run replaced code and aren't in KEEP_RUNNING are restarted, so a caller
    can't restart anything else."""
    refused = [unit for unit in units if not SERVICE_UNIT.fullmatch(unit) or not restartable(unit)]
    if refused:
        print(f"refusing to restart {', '.join(refused)}", file=sys.stderr)
        return 2
    stale = set(stale_services(proc))
    results: dict[str, str | None] = {}  # unit: why it failed, or None
    current = []
    for unit in dict.fromkeys(units):
        if unit not in stale:
            current.append(unit)
            continue
        # try-restart: a service that stopped meanwhile stays stopped.
        try:
            result = run(["systemctl", "try-restart", "--", unit], capture_output=True, text=True,
                         stdin=subprocess.DEVNULL, timeout=RESTART_TIMEOUT)
        except subprocess.TimeoutExpired:
            results[unit] = f"still restarting after {RESTART_TIMEOUT} seconds"
            continue
        except OSError as exc:
            results[unit] = f"cannot run systemctl: {exc.strerror or exc}"
            continue
        lines = (result.stderr or result.stdout).strip().splitlines()
        results[unit] = None if result.returncode == 0 else (
            lines[-1] if lines else f"systemctl exited with {result.returncode}")
    # A service whose processes outlive a restart (KillMode=process) keeps
    # the replaced code.
    stale = set(stale_services(proc))
    for unit, why in results.items():
        if why is None and unit in stale:
            results[unit] = "still runs replaced code after the restart"
    for unit in current:
        print(f"current {unit}")
    for unit, why in results.items():
        print(f"restarted {unit}" if why is None else f"failed {unit}: {why}")
    return 0 if all(why is None for why in results.values()) else 1


def main(argv: list[str] | None = None) -> int:
    argv = sys.argv[1:] if argv is None else argv
    if not argv or argv[0] not in VERBS or (len(argv) > 1) != (argv[0] == RESTART_SERVICES):
        print(f"usage: simple-update-helper {{{'|'.join(VERBS)}}}\n"
              f"       simple-update-helper {RESTART_SERVICES} UNIT...", 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")
    # pkexec and sudo keep the caller's umask. Maintainer scripts and hooks
    # would create system files with it: world-writable under 000,
    # unreadable to users under 077.
    os.umask(0o022)
    verb = argv[0]
    if verb == "services":
        for unit in stale_services():
            print(unit)
        return 0
    if verb == RESTART_SERVICES:
        return restart_services(argv[1:])
    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
    if verb in SUPERVISED:
        return run_supervised(verb, manager, command)
    if manager == "pacman" and verb == "clean":
        dbpath = pacman_dbpath()
        clear_stale_lock(dbpath)
        remove_partial_downloads(pacman_conf("CacheDir", PACMAN_CACHE), dbpath)
    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


def run_supervised(verb: str, manager: str, command: list[str]) -> int:
    """Run a package manager transaction so that it finishes even when the
    caller goes away, and so that the next start can tell when it didn't."""
    leave_session(verb)
    ignore_hangups()
    try:
        mark_running(verb)
    except OSError as exc:
        say(f"cannot record the run in {RUN_MARKER}: {exc.strerror or exc}")
    try:
        commands = [command]
        if manager == "pacman":
            clear_stale_lock(pacman_dbpath())
            if command[:2] == ["pacman", "-Syu"]:
                keyrings = pacman_keyrings()
                if keyrings:
                    status = upgrade_keyrings(keyrings)
                    if status != 0:
                        return status
                    commands = [["pacman", "-Su", "--noconfirm"]]
            if verb == "repair" and shutil.which("mkinitcpio"):
                # A run cut off during its post-transaction hooks can leave a
                # kernel without a matching initramfs, and -Syu with nothing
                # left to upgrade doesn't run the hooks again.
                commands.append(["mkinitcpio", "-P"])
        elif verb == "repair":
            commands.append(APT + APT_PROGRESS + ["-f", "install"])
        for argv in commands:
            status = supervise(argv)
            if status != 0:
                return status
        return 0
    finally:
        # A run that ended, even in failure, was not interrupted.
        clear_marker()


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