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

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

import os
import shutil
import subprocess
import sys

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

# Package prompts are hidden behind the progress view: take dpkg's default
# for changed configuration files, and keep the installed one otherwise.
APT = [
    "apt-get", "-y",
    "-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")


class UsageError(Exception):
    pass


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


def build_command(verb, manager, orphans=(), which=None):
    """The argv for a verb, or None when there is nothing to do."""
    which = which or shutil.which
    if verb == "refresh":
        if manager == "apt":
            return ["apt-get", "-o", "APT::Update::Error-Mode=any", "update"]
        return ["pacman", "-Sy", "--noconfirm"]
    if verb == "upgrade":
        if manager == "apt":
            return APT + APT_PROGRESS + ["upgrade"]
        # Always sync and upgrade together: never leave a partial upgrade.
        return ["pacman", "-Syu", "--noconfirm"]
    if verb == "dist-upgrade":
        if manager != "apt":
            raise UsageError("dist-upgrade is only available with apt")
        return APT + APT_PROGRESS + ["dist-upgrade"]
    if verb == "autoremove":
        if manager == "apt":
            return APT + APT_PROGRESS + ["autoremove"]
        return ["pacman", "-Rns", "--noconfirm", *orphans] if orphans else None
    if verb == "clean":
        if manager == "apt":
            return APT + ["autoclean"]
        return ["pacman", "-Sc", "--noconfirm"]
    if verb == "snap-refresh":
        return ["snap", "refresh"]
    if verb == "reboot":
        if which("systemd-run"):
            return ["systemd-run", "--on-active=2", "--quiet",
                    f"--unit=simple-update-reboot-{os.getpid()}", "systemctl", "reboot"]
        return ["shutdown", "-r", "+1"]
    raise UsageError(f"unknown verb: {verb}")


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


def 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")
    try:
        manager = detect_manager()
        verb = argv[0]
        orphans = pacman_orphans() if verb == "autoremove" and manager == "pacman" else ()
        command = build_command(verb, manager, orphans)
    except UsageError as exc:
        print(exc, file=sys.stderr)
        return 2
    if command is None:
        print("Nothing to do.")
        return 0
    sys.stdout.flush()
    try:
        os.execvp(command[0], command)
    except OSError as exc:
        print(f"cannot run {command[0]}: {exc}", file=sys.stderr)
        return 127


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