#!/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 json
import os
import re
import shutil
import signal
import subprocess
import sys
import syslog
import time

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", "repair")

# 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/")

PACMAN_CACHE = "/var/cache/pacman/pkg/"
PACMAN_DBPATH = "/var/lib/pacman/"
# 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):
    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):
    """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=None, os_release="/etc/os-release"):
    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, 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 == "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=None):
        self.stream = stream
        self.detached = False
        self.pending = b""

    def write(self, data: bytes):
        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):
        self.write(text.encode() + b"\n")


OUT = Output()


def say(text: str):
    OUT.say(text)


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


def logind_running():
    # 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, run=subprocess.run):
    """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():
    """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):
    """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):
    """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
    while chunk := proc.stdout.read1(65536):
        OUT.write(chunk)
    proc.stdout.close()
    return proc.wait()


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


def process_start_time(pid, proc="/proc"):
    """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, path=RUN_MARKER):
    """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=RUN_MARKER):
    try:
        os.unlink(path)
    except FileNotFoundError:
        pass


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 pacman_conf(key, default):
    """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 lock_is_held(lock, proc="/proc"):
    """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, proc="/proc"):
    """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, "db.lck")
    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():
    """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):
    """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, dbpath):
    """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, "db.lck")
    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="/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
    if verb in SUPERVISED:
        return run_supervised(verb, manager, command)
    if manager == "pacman" and verb == "clean":
        dbpath = pacman_conf("DBPath", PACMAN_DBPATH)[0]
        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, manager, command):
    """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_conf("DBPath", PACMAN_DBPATH)[0])
            if command[:2] == ["pacman", "-Syu"]:
                keyrings = pacman_keyrings()
                if keyrings:
                    status = upgrade_keyrings(keyrings)
                    if status != 0:
                        return status
                    commands = [["pacman", "-Su", "--noconfirm"]]
        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())
