#!/usr/bin/env python3
# summary: Check or install the remote desktop host.
"""starchaser sunshine status | install

Remote desktop is packaged in Starchaser's signed software source. Updates and setup use the package manager;
this helper never downloads or installs an upstream package behind its signature checks.
"""
import json
import os
import re
import shutil
import subprocess
import sys
from pathlib import Path

sys.path.insert(0, "/usr/local/lib/starchaser")
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "system/usr/local/lib/starchaser"))


def latest() -> dict:
    result = subprocess.run(["pacman", "-Si", "sunshine"], capture_output=True, text=True,
                            env=dict(os.environ, LC_ALL="C"), timeout=20)
    fields = dict(line.split(":", 1) for line in result.stdout.splitlines() if ":" in line and not line.startswith(" "))
    fields = {k.strip(): v.strip() for k, v in fields.items()}
    if result.returncode or fields.get("Repository") not in ("starchaser", "starchaser-testing") or not re.fullmatch(r"[0-9][0-9A-Za-z.+:_-]*", fields.get("Version", "")):
        raise RuntimeError("Sunshine isn't available from Starchaser's signed software source. Open Settings > Updates to refresh it.")
    return {"version": fields["Version"], "repository": fields["Repository"]}


def installed() -> str:
    result = subprocess.run(["pacman", "-Q", "sunshine"], capture_output=True, text=True)
    return result.stdout.split()[1] if not result.returncode and len(result.stdout.split()) > 1 else ""


def install() -> None:
    if os.geteuid() != 0:
        raise RuntimeError("Run this through Settings > Software.")
    release = latest()  # Refuse a same-name package from another software source.
    argv = ["pacman", "-S", "--needed", "--noconfirm", release["repository"] + "/sunshine"]
    import tested_releases
    tested_releases.guard_installer(argv)
    result = subprocess.run(argv)
    if result.returncode:
        raise RuntimeError("Remote desktop couldn't be installed. Open Settings > Updates for details.")


def main(argv: list) -> None:
    if argv[:1] in (["--help"], ["-h"], ["help"]) or argv[1:] in (["--help"], ["-h"]):
        print(__doc__); return
    if shutil.which("pacman") is None:
        raise RuntimeError("pacman isn't installed. Open Settings > Software after software setup finishes.")
    if len(argv) > 1 or (argv and argv[0] not in ("status", "install")):
        print("Usage: starchaser sunshine status | install", file=sys.stderr); raise SystemExit(2)
    if argv == ["install"]:
        install(); return
    try:
        version, error = latest()["version"], ""
    except RuntimeError as failure:
        version, error = "", str(failure)
    print(json.dumps({"installed": installed(), "latest": version, "source": "Starchaser", "error": error}))


if __name__ == "__main__":
    try:
        main(sys.argv[1:])
    except (RuntimeError, ValueError, OSError, subprocess.SubprocessError) as failure:
        print(str(failure), file=sys.stderr); raise SystemExit(1)
