#!/usr/bin/python3 -IS
"""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 verbs that take arguments
act only on what the helper finds itself: restart-services on units running
replaced code, config-use and config-remove on configuration files the
package manager left in /etc, firmware-update on devices fwupd offers an
update for. It is installed as a standalone script and must keep
to the standard library: -S skips the site module, so no installed package's
.pth file runs as root.
"""

import contextlib
import fcntl
import fnmatch
import io
import json
import os
import re
import resource
import shutil
import signal
import stat
import subprocess
import sys
import syslog
import time
from collections.abc import Callable, Container, Iterable, Iterator, 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"]

AUTO_UPDATES_ON = "auto-updates-on"
AUTO_UPDATES_OFF = "auto-updates-off"
# Clean Up's verbs: the whole package cache, Snap's disabled revisions and
# the system journal's old entries.
CLEAN_ALL = "clean-all"
SNAP_CLEAN = "snap-clean"
JOURNAL_CLEAN = "journal-clean"
# A configuration file the package manager left beside the one in use:
# config-use puts it in use, config-remove removes it. Both save the file
# they replace or remove under CONFIG_BACKUPS.
CONFIG_USE = "config-use"
CONFIG_REMOVE = "config-remove"
# Firmware Updates' verb, taking the fwupd device IDs to update.
FIRMWARE_UPDATE = "firmware-update"
RESTART_SERVICES = "restart-services"
VERBS = ("refresh", "upgrade", "dist-upgrade", "autoremove", "clean", "snap-refresh", "reboot",
         "services", RESTART_SERVICES, "repair", AUTO_UPDATES_ON, AUTO_UPDATES_OFF,
         CLEAN_ALL, SNAP_CLEAN, JOURNAL_CLEAN, CONFIG_USE, CONFIG_REMOVE, FIRMWARE_UPDATE)
# The verbs that take arguments, and need at least one: the units to
# restart, the configuration files to change, the devices to update.
TAKES_ARGUMENTS = (RESTART_SERVICES, CONFIG_USE, CONFIG_REMOVE, FIRMWARE_UPDATE)

# Automatic security updates are unattended-upgrades', run by apt's daily
# timers. Its switch is this file: the package's maintainer scripts read it
# back into debconf, and Ubuntu's Software & Updates writes it too.
UNATTENDED_UPGRADES = "unattended-upgrades"
UNATTENDED_UPGRADE_COMMAND = "unattended-upgrade"
AUTO_UPGRADES = "/etc/apt/apt.conf.d/20auto-upgrades"
UPDATE_LISTS = "APT::Periodic::Update-Package-Lists"
UNATTENDED_UPGRADE = "APT::Periodic::Unattended-Upgrade"
# apt-daily downloads the package lists, apt-daily-upgrade installs.
APT_TIMERS = ("apt-daily.timer", "apt-daily-upgrade.timer")
# apt's daily jobs, automatic updates among them, do nothing while this is 0.
PERIODIC_ENABLE = "APT::Periodic::Enable"
# Prints ENABLE='1', LISTS='1' and UPGRADE='1': the values in effect,
# whichever file under /etc/apt/apt.conf.d sets them. Unset ones are left out.
APT_PERIODIC = ["apt-config", "shell", "ENABLE", PERIODIC_ENABLE, "LISTS", UPDATE_LISTS,
                "UPGRADE", UNATTENDED_UPGRADE]

# dpkg's frontend lock. dpkg run with DPKG_FRONTEND_LOCKED set leaves it to
# its caller, as apt does, so the helper can wait for it first.
DPKG_FRONTEND_LOCK = "/var/lib/dpkg/lock-frontend"
DPKG_LOCK_WAIT = 120

# 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")
# Verbs that change package state without a transaction to supervise. They
# hold RUN_LOCK too, so they never interleave with a supervised verb: on
# Arch, clean locks pacman's database, which would fail an upgrade's next step.
LOCKED = ("refresh", "clean", "snap-refresh", CLEAN_ALL)

# What journal-clean keeps, in journalctl's time span syntax. The app
# estimates what it frees from JOURNAL_KEEP_DAYS.
JOURNAL_KEEP = "4weeks"
JOURNAL_KEEP_DAYS = 28

# Configuration files the package manager left beside the one in use, by
# the suffix it adds. Only those under CONFIG_ROOT are looked for.
CONFIG_ROOT = "/etc"
CONFIG_SUFFIXES = {
    "apt": (".dpkg-dist", ".dpkg-new", ".dpkg-old", ".ucf-dist"),
    "pacman": (".pacnew", ".pacsave"),
}
# Leftovers older than the file in use; the rest are newer versions the
# package shipped.
OLD_CONFIG_SUFFIXES = (".dpkg-old", ".pacsave")
# Unpacked by a dpkg run that didn't finish: finishing it (repair) puts the
# file in place, so it is left to dpkg.
UNFINISHED_CONFIG_SUFFIXES = (".dpkg-new",)
# Files config-use never replaces. A package's default for them can lock
# everyone out (accounts, sudo, PAM, SSH) or stop the system from starting
# (file systems, the initramfs, the boot loader), so they are merged by hand.
PROTECTED_CONFIG = (
    "/etc/passwd", "/etc/shadow", "/etc/group", "/etc/gshadow", "/etc/sudoers", "/etc/sudoers.d/*",
    "/etc/doas.conf", "/etc/pam.d/*", "/etc/security/*", "/etc/ssh/sshd_config",
    "/etc/ssh/sshd_config.d/*", "/etc/fstab", "/etc/crypttab", "/etc/mkinitcpio.conf",
    "/etc/mkinitcpio.d/*", "/etc/default/grub",
)
# Where config-use and config-remove save the file they replace or remove,
# in a directory for each run named after its time, under its own path:
# config-backups/20261117-214130/etc/pacman.conf. Root's alone: some
# configuration files hold secrets.
CONFIG_BACKUPS = "/var/lib/simple-update/config-backups"

# 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"
# Held by the supervised verb at work, so that only one runs at a time.
# Root's alone: a user who could open it could lock it and hold off updates.
RUN_LOCK = "/var/lib/simple-update/run.lock"
# What a supervised verb says when another one holds RUN_LOCK.
ALREADY_RUNNING = "Another Simple Update run is already in progress."
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/")

# The characters systemd allows in unit names, "\" included for escaped
# instance names (my\x2dvpn). Never starting with "-", so systemctl can't
# take one for an option, and never "*", "?" or "[", which it would expand.
SERVICE_UNIT = re.compile(r"[\w:\\][\w@.:\\-]*\.service", re.ASCII)
# 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",
)
# The alias display managers' units set (Alias= in [Install]), which names
# the one in use whether or not KEEP_RUNNING lists it.
DISPLAY_MANAGER = "display-manager.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}")
# What clean-all removes from pacman's cache: packages, their signatures
# and partial downloads. Anything else a CacheDir holds is left alone, so a
# CacheDir pointed somewhere unusual loses nothing but package files.
PACMAN_PACKAGE_FILE = re.compile(r".+\.pkg\.tar(\.\w+)?(\.sig)?(\.part)?")

# A snap's name and revision as `snap list --all` prints them: x1, x2...
# for snaps installed from a file.
SNAP_NAME = re.compile(r"[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", re.ASCII)
SNAP_REVISION = re.compile(r"x?\d+", re.ASCII)

# A device ID as fwupd prints it: a SHA-1 in hex. Never an option, a GUID or
# a file, which `fwupdmgr update` would also accept.
FWUPD_DEVICE_ID = re.compile(r"[0-9a-f]{40}", re.ASCII)
# Asked as root, fwupd would otherwise offer to upload reports or refresh
# old metadata; the app refreshes the metadata before it lists the updates.
FWUPD_QUIET = ["--no-unreported-check", "--no-metadata-check"]


class UsageError(Exception):
    pass


# Floors for the resource limits a caller hands down: pkexec and sudo keep
# them, and a package manager that hits one stops halfway (SIGXFSZ, a failed
# allocation, too few file descriptors). Limits are only ever raised.
RLIMIT_FLOORS = {
    resource.RLIMIT_FSIZE: resource.RLIM_INFINITY,
    resource.RLIMIT_CPU: resource.RLIM_INFINITY,
    resource.RLIMIT_AS: resource.RLIM_INFINITY,
    resource.RLIMIT_DATA: resource.RLIM_INFINITY,
    resource.RLIMIT_RSS: resource.RLIM_INFINITY,
    resource.RLIMIT_STACK: 8 * 1024 * 1024,
    resource.RLIMIT_MEMLOCK: 8 * 1024 * 1024,
    resource.RLIMIT_NOFILE: 1024,
}


def _raised(current: int, floor: int) -> int:
    if current == resource.RLIM_INFINITY or floor == resource.RLIM_INFINITY:
        return resource.RLIM_INFINITY
    return max(current, floor)


def reset_process_state(oom_score_adj: str = "/proc/self/oom_score_adj") -> None:
    """Undo what the caller can set for the processes it starts, which
    pkexec and sudo pass on to root: low resource limits, a raised OOM score
    or nice level, ignored or blocked signals, and the working directory.
    Each would let the caller stop the package manager halfway."""
    for limit, floor in RLIMIT_FLOORS.items():
        try:
            soft, hard = resource.getrlimit(limit)
        except (OSError, ValueError):
            continue
        wanted = _raised(soft, floor)
        try:
            resource.setrlimit(limit, (wanted, _raised(hard, wanted)))
        except (OSError, ValueError):
            # Raising a hard limit needs CAP_SYS_RESOURCE, which a container
            # can take from root: get as close as the hard limit allows.
            try:
                resource.setrlimit(limit, (hard, hard))
            except (OSError, ValueError):
                pass
    try:
        with open(oom_score_adj, "r+") as f:
            if int(f.read().strip() or 0) > 0:
                f.seek(0)
                f.write("0")
    except (OSError, ValueError):
        pass
    try:
        if os.getpriority(os.PRIO_PROCESS, 0) > 0:
            os.setpriority(os.PRIO_PROCESS, 0, 0)
    except OSError:
        pass
    # Ignored signals stay ignored across exec. Python ignores SIGPIPE
    # itself, and subprocess restores it for the commands it starts.
    for signum in signal.valid_signals():
        if signum in (signal.SIGKILL, signal.SIGSTOP, signal.SIGPIPE):
            continue
        try:
            if signal.getsignal(signum) == signal.SIG_IGN:
                signal.signal(signum, signal.SIG_DFL)
        except (OSError, ValueError):
            pass
    signal.pthread_sigmask(signal.SIG_SETMASK, set())
    os.chdir("/")


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


class UnsupportedSystem(UsageError):
    """The host must not be changed through apt or pacman."""


# Files whose presence marks an immutable system, whatever os-release says.
IMMUTABLE_MARKERS = ("/run/ostree-booted", "/usr/share/steamos")


def detect_manager(which: Callable[[str], str | None] | None = None,
                   os_release: str | os.PathLike[str] = "/etc/os-release",
                   markers: Sequence[str] | None = None) -> str:
    which = which or shutil.which
    markers = IMMUTABLE_MARKERS if markers is None else markers
    try:
        with open(os_release) as f:
            values = os_release_values(f.read())
    except OSError as exc:
        raise UnsupportedSystem("Cannot identify this system: /etc/os-release is unavailable.") from exc
    distro = values.get("ID", "")
    if (distro in {"steamos", "bazzite", "silverblue", "kinoite"}
            or values.get("VARIANT_ID") in {"silverblue", "kinoite", "sericea", "onyx", "coreos"}
            or any(os.path.exists(marker) for marker in markers)):
        raise UnsupportedSystem("Immutable systems are not supported. Use the system's own updater.")
    managers = {"debian": "apt", "ubuntu": "apt", "arch": "pacman",
                "manjaro": "pacman", "endeavouros": "pacman"}
    if distro not in managers:
        raise UnsupportedSystem(f"Unsupported distribution: {distro or 'unknown'}.")
    manager = managers[distro]
    binary = "apt-get" if manager == "apt" else "pacman"
    if not which(binary):
        raise UsageError(f"Required package manager not found: {binary}.")
    return manager


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 == CLEAN_ALL:
        if manager == "apt":
            return APT + ["clean"]
        # `pacman -Scc --noconfirm` takes the default answer, which keeps
        # every file; run_locked() empties the cache itself instead.
        return []
    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(run: Callable[..., Any] = subprocess.run) -> bool:
    """Whether systemd-inhibit can reach logind. Without it (containers)
    systemd-inhibit fails, and would take the command with it. Installing
    systemd creates /run/systemd/seats even where logind never runs, so
    logind is asked."""
    if not os.path.isdir("/run/systemd/seats") or not shutil.which("systemd-inhibit"):
        return False
    try:
        result = run(["systemd-inhibit", "--list", "--no-pager"], stdin=subprocess.DEVNULL,
                     stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=10)
    except (OSError, subprocess.TimeoutExpired):
        return False
    return bool(result.returncode == 0)


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():
        return argv
    return ["systemd-inhibit", "--what=sleep:shutdown", "--mode=block", "--who=Simple Update",
            "--why=Installing updates", *argv]


def supervise(argv: list[str], env: dict[str, str] | None = None) -> 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, env=env)
    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 claim_run(path: str) -> int:
    """Lock RUN_LOCK for this run and return the locked descriptor, which
    must stay open until the run ends. Only one supervised verb runs at a
    time, so one never replaces or removes the marker of another still at
    work. BlockingIOError means another holds the lock; the kernel drops it
    with its holder, so a dead helper never leaves it held."""
    os.makedirs(os.path.dirname(path), mode=0o755, exist_ok=True)
    fd = os.open(path, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)
    try:
        fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except OSError:
        os.close(fd)
        raise
    return fd


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."""
    _sweep_cache(cachedirs, dbpath, lambda name: name.endswith(".part"), report=True)


def empty_pacman_cache(cachedirs: Iterable[str], dbpath: str) -> int:
    """Delete every package file from pacman's cache, as `pacman -Scc`
    does, and the partial downloads. Returns 1 when some couldn't be."""
    return _sweep_cache(cachedirs, dbpath, PACMAN_PACKAGE_FILE.fullmatch, report=False)


def _sweep_cache(cachedirs: Iterable[str], dbpath: str, wanted: Callable[[str], object],
                 report: bool) -> int:
    """Delete the regular files in the cache directories whose names are
    wanted, and pacman 7's download directories. pacman's lock is held
    meanwhile, so a download in progress is never touched. report says
    each file removed; otherwise only how many. Returns 1 after a failure."""
    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(("Leaving partial downloads in place" if report else "Leaving the package cache as it is")
            + f": cannot lock {lock}: {exc.strerror}")
        return 1
    status = removed = 0
    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 wanted(entry.name) 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}")
                    status = 1
                    continue
                removed += 1
                if report:
                    say(f"removed {entry.path}")
    finally:
        os.close(lock_fd)
        os.unlink(lock)
    if not report:
        say(f"Removed {removed} file{'' if removed == 1 else 's'} from the package cache.")
    return status


def parse_snap_list_all(text: str) -> list[tuple[str, str]]:
    """The (name, revision) of each disabled revision in `snap list --all`:
    a "Name Version Rev Tracking Publisher Notes" header, then rows whose
    Notes include "disabled". Rows that don't look like a snap are skipped."""
    disabled = []
    for line in text.splitlines()[1:]:
        fields = line.split()
        if (len(fields) >= 6 and "disabled" in fields[-1].split(",")
                and SNAP_NAME.fullmatch(fields[0]) and SNAP_REVISION.fullmatch(fields[2])):
            disabled.append((fields[0], fields[2]))
    return disabled


def snap_clean() -> int:
    """Remove the revisions snapd keeps of each snap to roll back to. The
    helper finds them itself, so a caller can't remove a revision in use."""
    if not shutil.which("snap"):
        say("Snap is not installed.")
        return 1
    result = subprocess.run(["snap", "list", "--all"], capture_output=True, text=True)
    if result.returncode != 0:
        say(f"snap list failed: {result.stderr.strip()}")
        return 1
    disabled = parse_snap_list_all(result.stdout)
    if not disabled:
        say("Nothing to do.")
        return 0
    status = 0
    for name, revision in disabled:
        status = supervise(["snap", "remove", f"--revision={revision}", "--", name]) or status
    return status


def journal_clean(run: Callable[..., subprocess.CompletedProcess[Any]] = subprocess.run) -> int:
    """Delete the system journal's entries older than JOURNAL_KEEP. Only
    archived journal files can go, so the ones in use are archived first."""
    if not systemd_running() or not shutil.which("journalctl"):
        say("The system journal is not in use.")
        return 1
    sys.stdout.flush()
    # A failed rotation still leaves the older archived files to remove.
    run(["journalctl", "--rotate"], check=False)
    return int(run(["journalctl", f"--vacuum-time={JOURNAL_KEEP}"], check=False).returncode)


def config_leftovers(manager: str, root: str = CONFIG_ROOT) -> list[str]:
    """New or old configuration files waiting to be merged, such as
    .pacnew or .dpkg-dist, sorted. Unreadable directories are skipped, and
    symbolic links to directories aren't followed."""
    suffixes = CONFIG_SUFFIXES[manager]
    found = []
    for directory, _dirs, files in os.walk(root, onerror=lambda _e: None):
        found += [os.path.join(directory, name) for name in files if name.endswith(suffixes)]
    return sorted(found)


def config_original(path: str) -> str:
    """The file in use that a leftover such as foo.conf.pacnew belongs to."""
    return path.rsplit(".", 1)[0]


def config_protected(path: str) -> bool:
    """Whether the file a leftover belongs to is one of PROTECTED_CONFIG."""
    original = config_original(path)
    return any(fnmatch.fnmatchcase(original, pattern) for pattern in PROTECTED_CONFIG)


def config_verbs(path: str) -> tuple[str, ...]:
    """What may be done with a leftover: config-use unless its file is
    protected, and config-remove, except to what an unfinished dpkg run
    left, which only dpkg may change."""
    if path.endswith(UNFINISHED_CONFIG_SUFFIXES):
        return ()
    return (CONFIG_REMOVE,) if config_protected(path) else (CONFIG_USE, CONFIG_REMOVE)


class ConfigError(Exception):
    """Why a configuration file was left alone."""


def _regular_file(path: str) -> os.stat_result | None:
    """The file's status, or None when it doesn't exist. Raise ConfigError
    for anything but a regular file, such as a symbolic link."""
    try:
        st = os.lstat(path)
    except FileNotFoundError:
        return None
    if not stat.S_ISREG(st.st_mode):
        raise ConfigError(f"{path} is not a regular file; change it by hand")
    return st


def _trusted_directories(path: str, root: str) -> None:
    """Raise ConfigError unless every directory from the one holding path up
    to root is a real directory that only root can change. Otherwise another
    user could swap a file for a link between the checks and the changes."""
    root = os.path.normpath(root)
    directory = os.path.dirname(path)
    while True:
        try:
            st = os.lstat(directory)
        except FileNotFoundError:
            raise ConfigError(f"{path} no longer exists") from None
        if (not stat.S_ISDIR(st.st_mode) or st.st_uid != os.geteuid()
                or st.st_mode & (stat.S_IWGRP | stat.S_IWOTH)):
            raise ConfigError(f"other users can change {directory}; change {path} by hand")
        if directory == root or directory == os.path.dirname(directory):
            return
        directory = os.path.dirname(directory)


def save_config_backup(path: str, backups: str) -> str:
    """Copy a file into the run's backup directory under its own path, with
    its permissions, owner and times, and return the copy's path."""
    target = os.path.join(backups, path.lstrip("/"))
    os.makedirs(os.path.dirname(target), exist_ok=True)
    candidate, n = target, 1
    while os.path.lexists(candidate):  # the same file twice within a second
        candidate, n = f"{target}.{n}", n + 1
    shutil.copy2(path, candidate, follow_symlinks=False)
    st = os.lstat(path)
    os.chown(candidate, st.st_uid, st.st_gid)
    return candidate


def use_config(path: str, backups: str) -> str | None:
    """Put a leftover in place of the file it belongs to, which keeps its
    owner and permissions and is saved first. Returns where it was saved,
    or None when there was none (a removed package's .pacsave)."""
    leftover = _regular_file(path)
    if leftover is None:
        raise ConfigError(f"{path} no longer exists")
    original = config_original(path)
    current = _regular_file(original)
    backup = None
    if current is not None:
        backup = save_config_backup(original, backups)
        # Through a descriptor of the file checked above, never a link.
        fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC)
        try:
            st = os.fstat(fd)
            if (st.st_dev, st.st_ino) != (leftover.st_dev, leftover.st_ino):
                raise ConfigError(f"{path} changed meanwhile; change it by hand")
            # fchown() first: it clears set-user-ID and set-group-ID bits.
            os.fchown(fd, current.st_uid, current.st_gid)
            os.fchmod(fd, stat.S_IMODE(current.st_mode))
        finally:
            os.close(fd)
    # Atomic: the file in use is never missing or half written.
    os.replace(path, original)
    return backup


def remove_config(path: str, backups: str) -> str:
    """Remove a leftover, saving it first. Returns where it was saved."""
    if _regular_file(path) is None:
        raise ConfigError(f"{path} no longer exists")
    backup = save_config_backup(path, backups)
    os.unlink(path)
    return backup


def lock_package_manager(manager: str) -> Callable[[], None] | None:
    """Take the package manager's own lock, so that it doesn't write the
    configuration files meanwhile. Returns what releases it, or None after
    saying why it can't be had."""
    if manager == "apt":
        try:
            fd = hold_dpkg_frontend(DPKG_FRONTEND_LOCK)
        except OSError as exc:
            say(f"cannot lock {DPKG_FRONTEND_LOCK}: {exc.strerror or exc}")
            return None
        if fd is None:
            say("Another package manager is running. Try again once it is done.")
            return None
        return lambda: os.close(fd)
    dbpath = pacman_dbpath()
    clear_stale_lock(dbpath)
    lock = os.path.join(dbpath, PACMAN_LOCK)
    try:
        lock_fd = os.open(lock, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o000)
    except FileExistsError:
        say("pacman is running. Try again once it is done.")
        return None
    except OSError as exc:
        say(f"cannot lock {lock}: {exc.strerror or exc}")
        return None

    def release() -> None:
        os.close(lock_fd)
        os.unlink(lock)

    return release


def change_config(verb: str, paths: Sequence[str], manager: str, root: str = CONFIG_ROOT,
                  backups: str = CONFIG_BACKUPS, now: float | None = None) -> int:
    """config-use or config-remove each leftover, printing one line for
    each: "done<TAB>PATH<TAB>BACKUP" (BACKUP empty when nothing was saved)
    or "failed<TAB>PATH<TAB>why". Only leftovers the helper finds under root
    itself are changed, and only as config_verbs() allows, so a caller
    can't change any other file. Holds the package manager's lock."""
    found = set(config_leftovers(manager, root))
    refused = [path for path in paths if path not in found or verb not in config_verbs(path)]
    if refused:
        print(f"refusing to change {', '.join(refused)}", file=sys.stderr)
        return 2
    release = lock_package_manager(manager)
    if release is None:
        return 1
    try:
        # Root's alone, whatever the umask: some configuration files hold secrets.
        os.makedirs(backups, mode=0o700, exist_ok=True)
        os.chmod(backups, 0o700)
        run_backups = os.path.join(backups, time.strftime("%Y%m%d-%H%M%S", time.localtime(now)))
        ok = True
        for path in dict.fromkeys(paths):
            try:
                _trusted_directories(path, root)
                if verb == CONFIG_USE:
                    backup = use_config(path, run_backups)
                else:
                    backup = remove_config(path, run_backups)
            except ConfigError as exc:
                why = str(exc)
            except OSError as exc:
                why = f"{exc.filename or path}: {exc.strerror or exc}"
            else:
                print(f"done\t{path}\t{backup or ''}", flush=True)
                continue
            print(f"failed\t{path}\t{why}", flush=True)
            ok = False
        return 0 if ok else 1
    finally:
        release()
def fwupd_devices(text: str) -> list[dict[str, Any]]:
    """The devices in `fwupdmgr get-updates --json` that have an update,
    each with a valid "DeviceId" and a non-empty "Releases" list, newest
    release first. Anything else in the output is left out."""
    try:
        devices = json.loads(text).get("Devices")
    except (ValueError, AttributeError):
        return []
    if not isinstance(devices, list):
        return []
    return [device for device in devices
            if isinstance(device, dict) and isinstance(device.get("DeviceId"), str)
            and FWUPD_DEVICE_ID.fullmatch(device["DeviceId"])
            and isinstance(device.get("Releases"), list) and device["Releases"]
            and all(isinstance(release, dict) for release in device["Releases"])]


def firmware_update(device_ids: Sequence[str],
                    run: Callable[..., subprocess.CompletedProcess[str]] = subprocess.run) -> int:
    """Install the firmware fwupd offers for the named devices, one at a
    time, printing "updating ID" before each and "updated ID" or "failed ID:
    why" after it. The helper asks fwupd itself which devices have an
    update, so a caller can't install anything fwupd isn't offering: no
    downgrades, reinstalls or firmware files. Returns 1 when any failed."""
    if not shutil.which("fwupdmgr"):
        say("fwupd is not installed.")
        return 1
    listed = run(["fwupdmgr", "get-updates", "--json", *FWUPD_QUIET], stdin=subprocess.DEVNULL,
                 capture_output=True, text=True)
    if listed.returncode != 0:
        say(f"fwupdmgr get-updates failed: {(listed.stderr or listed.stdout).strip()}")
        return 1
    offered = {device["DeviceId"] for device in fwupd_devices(listed.stdout)}
    status = 0
    for device_id in dict.fromkeys(device_ids):
        if device_id not in offered:
            say(f"failed {device_id}: fwupd offers no update for this device")
            status = 1
            continue
        say(f"updating {device_id}")
        # supervise() holds off suspend and shutdown meanwhile: a device
        # that loses power while it is written can be left unusable. The
        # app offers the reboot itself, so fwupd mustn't ask.
        code = supervise(["fwupdmgr", "update", device_id, "--assume-yes", "--no-reboot-check",
                          "--no-device-prompt", *FWUPD_QUIET])
        if code == 0:
            say(f"updated {device_id}")
        else:
            say(f"failed {device_id}: fwupdmgr exited with {code}")
            status = 1
    return status


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", only: Container[str] | None = None) -> list[str]:
    """System services still running code from files an upgrade replaced,
    among those in only when it is given. 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, "cgroup")) as cgroup:
                unit = _service_unit(cgroup.read())
            if not unit or unit in units or (only is not None and unit not in only):
                continue
            with open(os.path.join(entry.path, "maps")) as maps:
                if not _maps_deleted_system_file(maps.read()):
                    continue
        except OSError:  # the process exited, or is a kernel thread
            continue
        units.add(unit)
    return sorted(units)


def display_manager(run: Callable[..., subprocess.CompletedProcess[str]] = subprocess.run) -> str | None:
    """The unit of the display manager in use, or None: what systemd's
    display-manager.service alias points to. Needs no root. Raise UsageError
    when the lookup fails, since that does not mean no display manager."""
    try:
        result = run(["systemctl", "show", "--property=Id", "--value", "--", DISPLAY_MANAGER],
                     capture_output=True, text=True, stdin=subprocess.DEVNULL, timeout=10)
    except (OSError, subprocess.TimeoutExpired) as exc:
        raise UsageError("Cannot determine the display manager; refusing service restarts.") from exc
    unit = result.stdout.strip()
    if result.returncode != 0 or not SERVICE_UNIT.fullmatch(unit):
        raise UsageError("Cannot determine the display manager; refusing service restarts.")
    # Without the alias, systemd reports the alias's own name.
    if unit == DISPLAY_MANAGER:
        return None
    return unit


def restartable(unit: str, display_manager_unit: str | None = None) -> bool:
    """Whether a service may be restarted without a reboot: a service unit
    name, not one of KEEP_RUNNING, and not the display manager in use."""
    return bool(SERVICE_UNIT.fullmatch(unit)) and unit != display_manager_unit and 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
    as soon as it is known: "restarted UNIT", "failed UNIT: why", or
    "current UNIT" when it no longer runs replaced code and was left alone.
    "restarting UNIT" comes before each restart, so a caller can show which
    one it is waiting for. Only services that still run replaced code and
    aren't in KEEP_RUNNING are restarted, so a caller can't restart anything
    else."""
    try:
        in_use = display_manager()
    except UsageError as exc:
        print(exc, file=sys.stderr)
        return 2
    refused = [unit for unit in units if not restartable(unit, in_use)]
    if refused:
        print(f"refusing to restart {', '.join(refused)}", file=sys.stderr)
        return 2
    stale = set(stale_services(proc))
    units = list(dict.fromkeys(units))
    for unit in units:
        if unit not in stale:
            print(f"current {unit}", flush=True)
    ok = True
    for unit in units:
        if unit not in stale:
            continue
        print(f"restarting {unit}", flush=True)
        why = _restart_service(unit, run)
        # A service whose processes outlive a restart (KillMode=process)
        # keeps the replaced code.
        if why is None and stale_services(proc, only={unit}):
            why = "still runs replaced code after the restart"
        print(f"restarted {unit}" if why is None else f"failed {unit}: {why}", flush=True)
        ok = ok and why is None
    return 0 if ok else 1


def _restart_service(unit: str, run: Callable[..., subprocess.CompletedProcess[str]]) -> str | None:
    """Why the service failed to restart, or None."""
    # 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:
        return f"still restarting after {RESTART_TIMEOUT} seconds"
    except OSError as exc:
        return f"cannot run systemctl: {exc.strerror or exc}"
    if result.returncode == 0:
        return None
    lines = (result.stderr or result.stdout).strip().splitlines()
    return lines[-1] if lines else f"systemctl exited with {result.returncode}"


def hold_dpkg_frontend(path: str = DPKG_FRONTEND_LOCK, wait: float = DPKG_LOCK_WAIT,
                       sleep: Callable[[float], object] = time.sleep) -> int | None:
    """Wait up to wait seconds for dpkg's frontend lock, as apt's
    DPkg::Lock::Timeout does, and return its locked descriptor, or None
    while another package manager (unattended-upgrades) still holds it.
    dpkg itself fails at once instead of waiting."""
    fd = os.open(path, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o640)
    deadline = time.monotonic() + wait
    while True:
        try:
            # dpkg and apt lock it with fcntl, as lockf() does.
            fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
            return fd
        except OSError:
            if time.monotonic() >= deadline:
                os.close(fd)
                return None
            sleep(1)


def configure_pending(command: list[str]) -> int:
    """Run `dpkg --configure -a` once no other package manager is at work."""
    try:
        lock = hold_dpkg_frontend()
    except OSError as exc:
        say(f"cannot open {DPKG_FRONTEND_LOCK}: {exc.strerror or exc}")
        return 1
    if lock is None:
        say(f"Could not get lock {DPKG_FRONTEND_LOCK}: another package manager is running.")
        return 1
    try:
        return supervise(command, env=dict(os.environ, DPKG_FRONTEND_LOCKED="1"))
    finally:
        os.close(lock)


def parse_apt_shell(text: str) -> dict[str, str]:
    """The NAME='value' lines `apt-config shell` prints."""
    return dict(re.findall(r"^(\w+)='(.*)'$", text, re.MULTILINE))


def periodic_on(value: str) -> bool:
    """Whether an APT::Periodic interval runs at all: "always", or a number
    of days, or a number with a unit. 0, or no value, turns it off."""
    value = value.strip().lower()
    match = re.fullmatch(r"(\d+)[smhd]?", value)
    return value == "always" or bool(match and int(match.group(1)) > 0)


def periodic_enabled(values: dict[str, str]) -> bool:
    """Whether APT::Periodic::Enable lets apt's daily jobs run, from
    parse_apt_shell(APT_PERIODIC). Unset means yes; apt.systemd.daily stops
    only when it is numerically 0."""
    try:
        return int(values.get("ENABLE", "1").strip()) != 0
    except ValueError:
        return True


def automatic_updates_configured(values: dict[str, str]) -> bool:
    """Whether the apt configuration in effect has unattended-upgrades run."""
    return (periodic_enabled(values) and periodic_on(values.get("LISTS", ""))
            and periodic_on(values.get("UPGRADE", "")))


def auto_upgrades_text(current: str | None, on: bool) -> str:
    """20auto-upgrades with unattended upgrades turned on or off, keeping
    whatever else it says. Turning them on refreshes the package lists too,
    without which there is nothing new to install. Starting from nothing, on
    is what the package itself installs."""
    wanted = {UPDATE_LISTS: "1", UNATTENDED_UPGRADE: "1"} if on else {UNATTENDED_UPGRADE: "0"}
    text = current or ""
    for key, value in wanted.items():
        setting = re.compile(rf'^(\s*{re.escape(key)}\s+)"[^"]*"', re.MULTILINE)
        if setting.search(text):
            text = setting.sub(rf'\g<1>"{value}"', text)
        else:
            text += ("" if not text or text.endswith("\n") else "\n") + f'{key} "{value}";\n'
    return text


def write_config(path: str, text: str) -> None:
    """Replace a configuration file at once. apt ignores the temporary
    file's name (~ at the end) should it be left behind."""
    temporary = f"{path}.simple-update~"
    with contextlib.suppress(FileNotFoundError):
        os.unlink(temporary)
    fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o644)
    with os.fdopen(fd, "w") as f:
        f.write(text)
        f.flush()
        os.fsync(f.fileno())
    os.replace(temporary, path)


@contextlib.contextmanager
def transaction(verb: str) -> Iterator[None]:
    """Run the body as a package manager transaction: outliving the caller,
    with the run marker present until it ends, so that the next start can
    tell when it never finished. The caller holds RUN_LOCK."""
    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:
        yield
    finally:
        # A run that ended, even in failure, was not interrupted.
        clear_marker()


def install_unattended_upgrades() -> int:
    """Install unattended-upgrades as a supervised transaction: like an
    upgrade, it goes on when the caller goes away. The package lists are
    refreshed first, so that the package can be found; a repository that
    can't be reached doesn't stop the installation."""
    with transaction(AUTO_UPDATES_ON):
        supervise(["apt-get", *APT_LOCK_WAIT, "update"])
        return supervise(APT + APT_PROGRESS + ["install", UNATTENDED_UPGRADES])


def set_auto_updates(on: bool, which: Callable[[str], str | None] = shutil.which,
                     run: Callable[..., subprocess.CompletedProcess[str]] = subprocess.run,
                     path: str = AUTO_UPGRADES) -> int:
    """Turn unattended-upgrades on or off, installing it first when needed.
    Holds RUN_LOCK, so it never runs alongside an update."""
    claim = _claim()
    if claim is None:
        return 1
    try:
        if which(UNATTENDED_UPGRADE_COMMAND) is None:
            if not on:
                say("Nothing to do.")
                return 0
            status = install_unattended_upgrades()
            if status != 0:
                return status
        try:
            with open(path) as f:
                current: str | None = f.read()
        except FileNotFoundError:
            current = None
        try:
            write_config(path, auto_upgrades_text(current, on))
        except OSError as exc:
            say(f"cannot write {path}: {exc.strerror or exc}")
            return 1
        if on and systemd_running():
            # They come enabled with apt, unless someone turned them off.
            status = run(["systemctl", "enable", "--now", *APT_TIMERS], check=False).returncode
            if status != 0:
                return status
        result = run(APT_PERIODIC, capture_output=True, text=True, check=False)
        values = parse_apt_shell(result.stdout)
        if on and not periodic_enabled(values):
            say(f'{PERIODIC_ENABLE} is "0" in /etc/apt/apt.conf.d, which turns off all of apt\'s '
                "daily jobs.")
            return 1
        if (periodic_on(values.get("UPGRADE", "")) != on
                or (on and not periodic_on(values.get("LISTS", "")))):
            say(f"{UNATTENDED_UPGRADE} is set in another file in /etc/apt/apt.conf.d, "
                f"which overrides {path}.")
            return 1
        say("Automatic security updates are on." if on else "Automatic security updates are off.")
        return 0
    finally:
        os.close(claim)


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] in TAKES_ARGUMENTS):
        plain = [verb for verb in VERBS if verb not in TAKES_ARGUMENTS]
        print(f"usage: simple-update-helper {{{'|'.join(plain)}}}\n"
              f"       simple-update-helper {RESTART_SERVICES} UNIT...\n"
              f"       simple-update-helper {{{CONFIG_USE}|{CONFIG_REMOVE}}} FILE...\n"
              f"       simple-update-helper {FIRMWARE_UPDATE} DEVICE-ID...", file=sys.stderr)
        return 2
    if argv[0] == FIRMWARE_UPDATE and not all(FWUPD_DEVICE_ID.fullmatch(arg) for arg in argv[1:]):
        print("device IDs are 40 lowercase hexadecimal digits", file=sys.stderr)
        return 2
    if os.geteuid() != 0:
        print("simple-update-helper must run as root", file=sys.stderr)
        return 2

    reset_process_state()
    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:])
    if verb == FIRMWARE_UPDATE:
        ids = argv[1:]
        return _locked(lambda: _detached(FIRMWARE_UPDATE, lambda: firmware_update(ids)))
    try:
        manager = detect_manager()
        if verb in (AUTO_UPDATES_ON, AUTO_UPDATES_OFF):
            if manager != "apt":
                # Arch has no security updates of their own to install, and
                # no partial upgrades.
                raise UsageError("automatic security updates are only available with apt")
            return set_auto_updates(verb == AUTO_UPDATES_ON)
        if verb == SNAP_CLEAN:
            return _locked(snap_clean)
        if verb == JOURNAL_CLEAN:
            return journal_clean()
        if verb in (CONFIG_USE, CONFIG_REMOVE):
            paths = argv[1:]
            return _locked(lambda: change_config(verb, paths, 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 verb in LOCKED:
        return run_locked(verb, manager, command)
    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 _claim() -> int | None:
    """RUN_LOCK's descriptor, or None after saying why it can't be had."""
    try:
        return claim_run(RUN_LOCK)
    except BlockingIOError:
        say(ALREADY_RUNNING)
    except OSError as exc:
        # Without the lock nothing keeps a second run out, so none starts.
        say(f"cannot lock {RUN_LOCK}: {exc.strerror or exc}")
    return None


def _locked(work: Callable[[], int]) -> int:
    """work(), holding RUN_LOCK, so it never runs alongside an update."""
    claim = _claim()
    if claim is None:
        return 1
    try:
        return work()
    finally:
        os.close(claim)


def _detached(verb: str, work: Callable[[], int]) -> int:
    """work(), carrying on when the caller goes away, like a transaction
    but without the run marker: firmware writes aren't a package manager
    transaction to repair, and one cut off halfway can leave a device
    unusable."""
    leave_session(verb)
    ignore_hangups()
    return work()


def run_locked(verb: str, manager: str, command: list[str]) -> int:
    """Run command attached to the caller, sharing RUN_LOCK with the child
    so the lock survives if the helper exits before the command does."""
    claim = _claim()
    if claim is None:
        return 1
    try:
        if manager == "pacman" and verb in ("clean", CLEAN_ALL):
            dbpath = pacman_dbpath()
            clear_stale_lock(dbpath)
            cachedirs = pacman_conf("CacheDir", PACMAN_CACHE)
            if verb == CLEAN_ALL:
                return empty_pacman_cache(cachedirs, dbpath)
            remove_partial_downloads(cachedirs, dbpath)
        sys.stdout.flush()
        # The command holds the lock too, so that it stays held if the
        # helper is stopped first. Whatever the command leaves running in
        # the background holds it as well, until it exits: a later run then
        # waits for nothing and says another is in progress.
        try:
            status = subprocess.run(command, check=False, pass_fds=(claim,)).returncode
        except OSError as exc:
            print(f"cannot run {command[0]}: {exc}", file=sys.stderr)
            return 127
        except KeyboardInterrupt:  # Ctrl-C reached the command too
            return 130
        # Killed by a signal: report it the way a shell does.
        return 128 - status if status < 0 else status
    finally:
        os.close(claim)


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."""
    claim = _claim()
    if claim is None:
        return 1
    try:
        with transaction(verb):
            return _run_transaction(verb, manager, command)
    finally:
        os.close(claim)


def _run_transaction(verb: str, manager: str, command: list[str]) -> int:
    """The commands of a supervised verb, stopping at the first failure."""
    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":
        # dpkg doesn't wait for the lock like apt does, so it would fail
        # while unattended-upgrades runs.
        status = configure_pending(command)
        if status != 0:
            return status
        commands = [APT + APT_PROGRESS + ["-f", "install"]]
    for argv in commands:
        status = supervise(argv)
        if status != 0:
            return status
    if verb == "autoremove" and manager == "pacman":
        return _remove_new_orphans(set(command[command.index("--") + 1:]))
    return 0


# Enough for any chain of optional dependencies seen in practice; the limit
# only keeps a misbehaving pacman from looping forever.
ORPHAN_PASSES = 10


def _remove_new_orphans(removed: set[str]) -> int:
    """Remove what the last removal left unneeded, until nothing is. -Qdt
    leaves out packages that an installed one lists as optional, and -Rns
    never removes optional dependencies: removing their last user turns
    them into orphans that a single pass would leave for the next run."""
    for _ in range(ORPHAN_PASSES):
        orphans = pacman_orphans()
        # Ones it already removed would mean pacman didn't; stop rather
        # than try again.
        if not orphans or removed.intersection(orphans):
            break
        status = supervise(["pacman", "-Rns", "--noconfirm", "--", *orphans])
        if status != 0:
            return status
        removed.update(orphans)
    return 0


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