#!/usr/bin/env python3
# summary: Switch an existing desktop to package updates.
"""One-time switch from copied Starchaser files to package updates."""
import json
import os
import pwd
import signal
import subprocess
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
from starchaser_cli import CommandParser

sys.dont_write_bytecode = True
for _lib in (Path(__file__).resolve().parent.parent / "system/usr/local/lib/starchaser", Path("/usr/local/lib/starchaser")):
    if (_lib / "pkgrepo.py").is_file():
        sys.path.insert(0, str(_lib))
        break
import pkgrepo

ADMIN = "/usr/local/lib/starchaser/starchaser-admin"


def main(argv=None):
    args = pkgrepo.switch_parser(parser_class=CommandParser).parse_args(argv)
    args.user = args.user or pwd.getpwuid(os.getuid()).pw_name
    if args.dry_run or os.geteuid() == 0:
        return pkgrepo.run_switch(args)
    pkgrepo.validate_user(args.user, os.getuid())
    pkgrepo.require_admin(args.user)
    facts = pkgrepo.switch_facts()
    if facts["installed"] and pkgrepo.setup_finished(args.user):
        print("starchaser-desktop is already installed. This computer already uses the package.")
        return 0
    # Validate the inputs before asking for a password.
    pkgrepo.switch_plan(args.user, args.channel, args.repo_url, args.package_dir, args.keyring, **facts)
    try:
        result = subprocess.run([ADMIN, "commands"], capture_output=True, text=True, check=True)
        ready = "switch-to-package" in json.loads(result.stdout).get("commands", [])
    except (OSError, ValueError, subprocess.CalledProcessError):
        ready = False
    if not ready:
        raise ValueError("Run the Starchaser setup again first; this computer's admin helper needs the switch command.")
    cmd = ["pkexec", ADMIN, "switch-to-package", "--channel", args.channel, "--repo-url", args.repo_url]
    for flag, value in (("--package-dir", args.package_dir), ("--keyring", args.keyring)):
        if value:
            cmd += [flag, str(value.resolve())]
    result = subprocess.run([*cmd, "--user", args.user], stderr=subprocess.PIPE, text=True)
    if result.returncode in (126, 127):
        raise ValueError("Administrator permission wasn't granted. Run this from a terminal on the computer, "
                         "or use --dry-run to preview the change.")
    if result.stderr:
        sys.stderr.write(result.stderr)
    return result.returncode


if __name__ == "__main__":
    # A reader such as head may close stdout after it has all it needs: the write ends this quietly, no Python error
    signal.signal(signal.SIGPIPE, signal.SIG_DFL)
    try:
        sys.exit(main())
    except (OSError, ValueError, subprocess.CalledProcessError) as e:
        sys.exit(f"starchaser switch to package: {e}")
