#!/usr/bin/env python3
"""starchaser-admin-area: runs one of Starchaser's system changes, such as USB protection, remote login or
going back to a snapshot, so the password box names the change.

It checks that the command is one of the ones below and runs starchaser-admin with it, unchanged.

    starchaser-admin-area usb-level relaxed|strict|off    USB device protection
    starchaser-admin-area usb-setup
    starchaser-admin-area ssh on|off                      remote login
    starchaser-admin-area autologin on|off                signing in by itself after a restart
    starchaser-admin-area hostname <name>                 renaming this computer
    starchaser-admin-area recovery-undo <number> [...]    go back to a snapshot
    starchaser-admin-area recovery-go-back-undo <number>  undo the last go-back
    starchaser-admin-area recovery-snapshot-go-back <number>  go back to the snapshot this computer started from
    starchaser-admin-area recovery-create [label]         take / delete / keep snapshots, rebuild the startup files
    starchaser-admin-area recovery-delete <number>
    starchaser-admin-area recovery-keep
    starchaser-admin-area recovery-boot
    starchaser-admin-area firewall-*                      the firewall's changes (see starchaser-admin); the -quick ones
                                                          only run a change that tightens, so polkit may let them
                                                          through during a sitting (49-starchaser-firewall-authorization.rules)
    starchaser-admin-area pacman-unlock                   clear a lock an unfinished install left behind (Recovery)
    starchaser-admin-area printing-on                     turn on printing (Printers)
    starchaser-admin-area backup-folder <mount point>     make your backup folder on a drive (Backups)
"""
# Why this program exists (decided 2026-10-10; not shown in --help):
# the door Settings uses so the password box names the change (decided 2026-10-10: "USB
# protection", "remote login", "go back to the snapshot you picked" instead of "make changes to this computer").
#
# pkexec picks the polkit action by the program's path and, when an action says so, its first argument
# (org.freedesktop.policykit.exec.argv1). On starchaser-admin itself that can't work: org.starchaser.admin matches
# that path with no argument, and pkexec takes the FIRST action whose path matches, in no set order (checked on qa-8,
# polkit 127: every command still got the generic message). This program's path has only actions that name their
# command (org.starchaser.areas.policy), so each command gets its own message, and nothing else can match.
# Still the password every time (auth_admin): only the words differ from org.starchaser.admin.
#
# It runs nothing on its own: it checks that the command is one of the ones below and runs starchaser-admin with it,
# unchanged (same environment, so PKEXEC_UID still says who asked). Installed root-owned beside starchaser-admin, so
# code the user can edit never runs as root. A caller that doesn't find it (older system tools) uses starchaser-admin.
import json
import os
import subprocess
import sys

ADMIN = os.path.join(os.path.dirname(os.path.realpath(__file__)), "starchaser-admin")
# command -> (fewest, most) words after it; each has its own action in org.starchaser.areas.policy
ALLOWED = {"update-restart-tonight": (1, 1), "firmware-refresh": (0, 0), "firmware": (1, 1), "drive-unlock": (1, 1), "hardware-fix": (1, 1), "hardware-restart": (1, 1), "usb-level": (1, 1), "usb-setup": (0, 0), "ssh": (1, 1), "autologin": (1, 1), "hostname": (1, 1),
           "recovery-undo": (1, 2), "recovery-go-back-undo": (1, 2), "recovery-create": (0, 2), "recovery-delete": (1, 1), "recovery-keep": (0, 0),
           "recovery-boot": (0, 1), "recovery-snapshot-go-back": (1, 1), "pacman-unlock": (0, 0), "printing-on": (0, 0), "backup-folder": (1, 1),
           "firewall-commit": (1, 9), "firewall-commit-quick": (1, 9), "firewall-rollback-quick": (1, 5), "firewall-password-mode": (1, 1), "firewall-rollback": (1, 5), "firewall-revert": (0, 1),
           "firewall-reload": (0, 1), "firewall-restart-outgoing": (0, 0), "firewall-allow-always": (3, 9), "firewall-mark-network": (2, 3),
           "firewall-forget-asked": (1, 1), "firewall-revoke-once": (3, 5), "firewall-public-pause-on": (0, 0), "firewall-public-pause-off": (0, 1)}


def main(argv: list) -> None:
    cmd = argv[0] if argv else ""
    if cmd in ("-h", "--help", "help") or any(a in ("-h", "--help") for a in argv[1:]):
        print(__doc__.strip())
        return
    if cmd == "commands":                              # read-only, like starchaser-admin's own
        print(json.dumps({"ok": True, "commands": sorted(ALLOWED)}))
        return
    lo, hi = ALLOWED.get(cmd, (-1, -1))
    if cmd not in ALLOWED and cmd and not cmd.startswith("-"):   # a newer Settings asking older system tools
        package = os.path.exists("/usr/share/starchaser/installer/starchaser-desktop-setup.sh")
        print(json.dumps({"ok": False, "errors": "Nothing was changed: this part of Settings needs a newer version of Starchaser's system tools. " + (
            "Open Settings > Updates and install the available updates to bring them up to date." if package else
            "This copy was installed from a developer checkout, so run the checkout's setup again to bring it up to date."),
            "unknown": cmd[:40]}))
        sys.exit(2)
    if not lo <= len(argv) - 1 <= hi:
        print(json.dumps({"ok": False, "errors": "starchaser-admin-area doesn't do that; nothing was changed."}))
        sys.exit(2)
    if os.geteuid() != 0:
        print(json.dumps({"ok": False, "errors": "run through pkexec"}))
        sys.exit(1)
    if cmd == "update-restart-tonight":
        if argv[1] not in ("tonight", "tonight-off"):
            sys.exit(2)
        argv = ["autoupdate-set", argv[1]]
    if cmd == "firmware-refresh":
        argv = ["firmware", "refresh"]
    if cmd.startswith("firewall-"):
        # Keep pkexec's PID/start time and the original Settings parent intact:
        # the admin dispatcher consumes the token issued to this exact process.
        os.execv(ADMIN, [ADMIN] + argv)
    sys.exit(subprocess.call([ADMIN] + argv))


if __name__ == "__main__":
    main(sys.argv[1:])
