#!/usr/bin/env python3
# summary: Show detected hardware and available repairs.
"""starchaser hardware: show detected hardware or repair one item through the system permission helper.

Usage: starchaser hardware get
       starchaser hardware fix <item>
       starchaser hardware restart wifi|bluetooth|sound|touchpad

    starchaser hardware restart wifi|bluetooth|sound|touchpad   first aid without rebooting
    starchaser hardware get          JSON: each kind of hardware found, with an "id" and what is missing, if anything
    starchaser hardware fix <item>   install what that item is missing; <item> is an "id" from get
Fixing changes the system, so it asks for your password.
"""
import json
import subprocess
import sys
from pathlib import Path

for lib in (Path(__file__).resolve().parents[1] / "system/usr/local/lib/starchaser", Path("/usr/local/lib/starchaser")):
    if (lib / "hardware.py").is_file():
        sys.path.insert(0, str(lib))
        break
import hardware


def main(args):
    if args in (["-h"], ["--help"], ["help"]):
        print(__doc__.strip())
        return 0
    if args and args[0] in ("get", "fix", "restart") and any(a in ("-h", "--help", "help") for a in args[1:]):
        # a help request after a command shows that command's usage; it is never an item name to look up
        print(__doc__.strip())
        return 0
    if len(args) == 2 and args[0] == "restart" and args[1] in ("wifi", "bluetooth", "sound", "touchpad"):
        try:
            if args[1] == "sound":
                restarted = subprocess.run(["systemctl", "--user", "restart", "pipewire.service", "pipewire-pulse.service", "wireplumber.service"], capture_output=True, text=True, timeout=30)
                healthy = subprocess.run(["wpctl", "status"], capture_output=True, text=True, timeout=10)
                if restarted.returncode or healthy.returncode:
                    raise ValueError("Sound couldn't restart. Reconnect USB speakers or headphones, then try again.")
                print(json.dumps({"ok": True, "message": "Sound restarted. Try playing something."}))
                return 0
            if args[1] == "wifi":
                hardware.check_wifi()
            if args[1] == "bluetooth":
                hardware.check_bluetooth()
            result = subprocess.run(["pkexec", "/usr/local/lib/starchaser/starchaser-admin-area", "hardware-restart", args[1]], capture_output=True, text=True)
            if not result.stdout.strip():
                raise ValueError("The restart was canceled or couldn't finish. Try again.")
            payload = json.loads(result.stdout)
            print(json.dumps(payload))
            return 0 if result.returncode == 0 and payload.get("ok") else 1
        except (OSError, ValueError, subprocess.SubprocessError) as error:
            print(json.dumps({"ok": False, "errors": str(error)}))
            return 1
    if args == ["get"]:
        try:
            print(json.dumps({"ok": True, "items": hardware.status()}))
            return 0
        except (OSError, ValueError, subprocess.SubprocessError):
            message = "Hardware couldn't be checked. Try Check again."
    elif len(args) == 2 and args[0] == "fix" and args[1] in hardware.ITEMS | hardware.quirk_ids():
        # nothing missing: say so in the same words the root helper would, without opening a password box
        try:
            row = next((r for r in hardware.status() if r["id"] == args[1] and r["detected"]), None)
        except (OSError, ValueError, subprocess.SubprocessError):
            row = None
        if row is not None and not row["needsFix"]:
            print(json.dumps({"ok": True, "message": row["detail"]}))
            return 0
        # Only root-owned code chooses packages. The item is checked again after permission is granted.
        p = subprocess.run(["pkexec", "/usr/local/lib/starchaser/starchaser-admin-area", "hardware-fix", args[1]],
                           capture_output=True, text=True)
        if p.returncode in (126, 127) and not (p.stdout or "").strip():
            # pkexec's own words name its terminal and its agent, not what to do: the plain message the sibling
            # tools use, on stderr for a terminal and in the JSON Settings reads (126 = the password box was closed)
            msg = ("Not changed: you closed the password box." if p.returncode == 126
                   else "No password window opened, so the change didn't start. Sign out and back in, then try again."
                   if "authentication agent" in (p.stderr or "").lower() or "/dev/tty" in (p.stderr or "").lower()
                   else "Couldn't get permission. Try again; if no password box appears, sign out and back in.")
            print(json.dumps({"ok": False, "errors": msg}))
            print(msg, file=sys.stderr)
            return 1
        if p.stdout:
            print(p.stdout, end="" if p.stdout.endswith("\n") else "\n")
        if p.stderr:
            sys.stderr.write(p.stderr if p.stderr.endswith("\n") else p.stderr + "\n")
        return p.returncode
    elif len(args) == 2 and args[0] == "fix":
        message = (f"No hardware item called '{args[1]}'. Items: {', '.join(sorted(hardware.ITEMS))}. "
                   "Run 'starchaser hardware get' to see what each one is (1002 is AMD, 10de is NVIDIA, 8086 is Intel).")
    else:
        if not args or args[0] not in ("get", "fix", "restart"):
            print(f"starchaser hardware: unknown command {args[0]!r}. Run 'starchaser hardware --help' for more help."
                  if args else "starchaser hardware: missing command. Run 'starchaser hardware --help' for more help.",
                  file=sys.stderr)
        else:
            print(f"starchaser hardware: wrong arguments for {args[0]!r}.", file=sys.stderr)
        print("Usage: starchaser hardware get\n       starchaser hardware fix <item>\n"
              "       starchaser hardware restart wifi|bluetooth|sound|touchpad", file=sys.stderr)
        return 2
    print(json.dumps({"ok": False, "errors": message}))
    return 1


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