#!/usr/bin/env python3
"""starchaser-remote-desktop: the root steps remote desktop in your fleet needs, which a paired device can trigger
(through starchaser link) without a password prompt. Root-owned in /usr/local/lib/starchaser/; polkit action
org.starchaser.remote-desktop, allowed for the wheel group by /etc/polkit-1/rules.d/50-starchaser-remote-desktop.rules.
It does exactly these things and nothing else:

    starchaser-remote-desktop allow         let Sunshine (and mDNS, for discovery) through the firewall on the fleet's
                                            networks (your own networks, plus Tailscale/VPN as their switches say)
                                            when no rule concerns it (no-op when the firewall is off). A rule that names
                                            it or its ports is the person's decision and stays as it is: an allow reports
                                            "already allowed" or "limited to certain devices or ports in the firewall", a
                                            block (or an allow switched off) "turned off in the firewall". Otherwise the
                                            any-device allow goes at the END of the list, behind every rule, unless a
                                            block for every device would leave it unreachable ("turned off"). See standing().
                                            The Sunshine allow covers its streaming ports only (a chosen service), never
                                            its web page. If a firewall change is waiting for Keep, the policy the
                                            countdown would go back to gets the same opening, so it isn't taken away
                                            and the waiting change is still kept only by Keep.
    starchaser-remote-desktop disallow      the last device allowed remote desktop here is gone and the person said
                                            to turn it off: take out only the openings allow added (the rules it
                                            recorded, or Sunshine's streaming-only rule, still as it made them). A rule
                                            the person made or changed stays. Only makes the firewall stricter.
    starchaser-remote-desktop wake-on-lan   keep magic-packet wake on for every wired connection; reports which it
                                            changed ("changed"), so the person is told (starchaser link)
"""
import importlib.machinery
import importlib.util
import json
import os
import re
import shutil
import subprocess
import sys
from pathlib import Path

sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))
import firewall as fw  # the engine, root-owned beside this file
import firewall_access

_admin = None


def admin():
    """starchaser-admin, beside this file: its lock and its record of a change waiting for Keep (one firewall
    change at a time, and the countdown's "go back to" policy, are its business)."""
    global _admin
    if _admin is None:
        path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "starchaser-admin")
        loader = importlib.machinery.SourceFileLoader("starchaser_admin", path)
        spec = importlib.util.spec_from_loader("starchaser_admin", loader)
        _admin = importlib.util.module_from_spec(spec)
        loader.exec_module(_admin)
    return _admin


# What a paired device needs to reach, from the fleet's networks: Sunshine's streaming ports (not its web page,
# 47990, which stays on this computer) and mDNS, so Moonlight (and the fleet) can find this machine. Inbound
# multicast is dropped by default, so without mDNS the host only shows up when Sunshine starts and announces itself.
# The networks are fw.fleet_zones() (your own networks, Tailscale and VPN by their switches; read once, this helper
# runs once per request).
ZONES = tuple(fw.fleet_zones())
# the openings allow() added, by rule id, so disallow() takes out exactly those
ADDED = Path("/var/lib/starchaser/remote-desktop.json")
NEEDS = (("sunshine", "Remote desktop (Sunshine)",
          [("tcp", 47984), ("tcp", 47989), ("tcp", 48010), ("udp", 47998), ("udp", 47999), ("udp", 48000),
           ("udp", 48002), ("udp", 48010)]),
         ("mdns", "Finding nearby devices", [("udp", 5353)]))
# The Sunshine allow names these ports as a service of its own: the catalog's Sunshine entry (app-default) also
# lists its web page (tcp 47990), which must not open to the network.
STREAM = {"id": "starchaser-remote-desktop", "name": "Remote desktop streaming (Sunshine)",
          "ports": [f"{pr}:{n}" for pr, n in NEEDS[0][2]]}


def standing(policy: dict, app: str, ports: list, cat: dict, live: dict) -> str:
    """How the firewall treats the app on the fleet's networks, and so what allow() does about it: "open",
    "limited" or "off" (a rule of the person's decides, or would still turn a new allow away), or "none" (add the
    any-device allow at the end). firewall_access.standing() owns the decision table; here an allow for the app
    that the person switched off also counts as "off"."""
    return firewall_access.standing(fw, policy, ZONES, (app,), ports, cat, live,
                                    lambda p: add_allow(p, app, "", "b-trial"), switched_off=True)


def added_rule(app: str, name: str, rid: str) -> dict:
    """The narrow allow a paired device adds: the fleet's networks, any device there, only the ports in NEEDS
    (for Sunshine its streaming ports, through the STREAM service; add it with add_allow())."""
    return firewall_access.basic_allow(rid, name, app, ZONES, [STREAM["id"]] if app == "sunshine" else "app-default")


def add_allow(policy: dict, app: str, name: str, rid: str = "") -> dict:
    """The policy with added_rule() at the end (and the STREAM service it names, if it isn't there yet)."""
    rules = list(policy.get("rules") or [])
    rid = rid or firewall_access.next_id(policy, app)
    services = list(policy.get("services") or [])
    if app == "sunshine":
        services = [s for s in services if s.get("id") != STREAM["id"]] + [dict(STREAM)]
    return dict(policy, rules=rules + [added_rule(app, name, rid)], services=services)


def allow() -> dict:
    adm = admin()
    with adm.locked():                                   # one firewall change at a time (starchaser-admin's lock)
        return _allow(adm)


def recorded() -> list:
    try:
        ids = json.loads(ADDED.read_text()).get("rules")
    except (OSError, ValueError, AttributeError):
        return []
    return [i for i in ids if isinstance(i, str)] if isinstance(ids, list) else []


def record(ids: list) -> None:
    fw.write_atomic(ADDED, json.dumps({"rules": sorted(set(ids))}) + "\n", mode=0o644)


def ours(r: dict, ids: list, stream_ok: bool = True) -> bool:
    """A rule allow() added, still as it made it: recorded by id (or Sunshine's streaming-only rule, which only allow()
    makes), an any-device allow on the fleet's networks with the ports allow() gave it. Edited by the person (other
    networks, some devices, its own ports or service, switched off), it's theirs now. stream_ok: the streaming port
    group itself is still as allow() made it (a group the person edited makes the rules using it theirs)."""
    want = [STREAM["id"]] if r.get("app") == "sunshine" else "app-default"
    if not (r.get("managed") == "basic" and r.get("dir") == "in" and r.get("action") == "allow"
            and r.get("app") in ("sunshine", "mdns") and r.get("enabled", True) and fw.is_fleet_rule(r)
            and r.get("user", "any") == "any" and r.get("service") == want and (stream_ok or want == "app-default")):
        return False
    if r.get("id") in ids:
        return True
    return r.get("app") == "sunshine"


def stream_as_made(policy: dict) -> bool:
    """The streaming port group in this policy is still allow()'s (same ports), or isn't there at all."""
    for x in policy.get("services") or []:
        if isinstance(x, dict) and x.get("id") == STREAM["id"]:
            return sorted(x.get("ports") or []) == sorted(STREAM["ports"])
    return True


def without_ours(policy: dict, ids: list) -> tuple:
    """(policy without allow()'s openings, the ids taken out): the streaming port group goes too once no rule uses it."""
    ok = stream_as_made(policy)
    rules = list(policy.get("rules") or [])
    keep = [r for r in rules if not ours(r, ids, ok)]
    gone = [r.get("id") for r in rules if ours(r, ids, ok)]
    new = dict(policy, rules=keep)
    if gone and not any(r.get("service") == [STREAM["id"]] for r in keep):
        new["services"] = [x for x in policy.get("services") or [] if x.get("id") != STREAM["id"]]
    return new, gone


def disallow() -> dict:
    adm = admin()
    with adm.locked():
        return _disallow(adm)


def _disallow(adm) -> dict:
    try:
        policy = json.loads(fw.POLICY.read_text())
    except (OSError, ValueError):
        return {"ok": True, "changed": False, "why": "no firewall policy"}
    ids = recorded()
    # A change waiting for Keep (even one that turned the firewall off, or one that already took the opening out):
    # the policy it would go back to loses the same openings, so going back, the countdown or a restart can't bring
    # remote desktop's firewall opening back after it was turned off
    w = adm.waiting()
    old_w = json.loads(json.dumps(w)) if w else None
    if w and isinstance(w.get("prev"), dict):
        pnew, pgone = without_ours(w["prev"], ids)
        if pgone:
            try:
                w["prev"] = fw.validate(pnew)
                w["prevNft"] = None
                adm.save_waiting(w)
            except fw.PolicyError:
                pass                                     # leave the way back as it was
    new, gone = without_ours(policy, ids)
    if not gone:
        record([])
        return {"ok": True, "changed": False, "why": "nothing of ours"}
    try:
        clean = fw.validate(new)
    except fw.PolicyError as e:
        if old_w:
            adm.save_waiting(old_w)
        return {"ok": False, "errors": str(e)}
    if not policy.get("enabled"):
        # the firewall is off: only the saved policy changes (nothing is open because of it now)
        fw.write_atomic(fw.POLICY, json.dumps(clean, indent=2) + "\n")
        record([])
        return {"ok": True, "changed": True, "removed": gone}
    err = firewall_access.load(fw, adm, clean, "Remote desktop turned off: its firewall opening was taken out", w, old_w)
    if err:
        return {"ok": False, "errors": err}
    record([])
    return {"ok": True, "changed": True, "removed": gone}


def _allow(adm) -> dict:
    try:
        policy = json.loads(fw.POLICY.read_text())
    except (OSError, ValueError):
        return {"ok": True, "changed": False, "why": "no firewall policy"}
    if not policy.get("enabled"):
        return {"ok": True, "changed": False, "why": "firewall off"}
    try:
        policy = fw.validate(policy)
    except fw.PolicyError as e:
        return {"ok": False, "errors": str(e)}
    cat, live = fw.catalog(), fw.listening()
    before = list(policy.get("rules") or [])
    # The person's rules always win: a paired device never switches a block (or an allow they turned off) back
    # on, never widens an allow they limited to some devices, and never puts a rule ahead of theirs. Only when no
    # rule at all concerns it (just the default) is the narrow allow added (the fleet's networks, any device
    # there), and at the end of the list, so it only catches what the default would have turned away.
    added, off, limited = [], [], []
    for app, name, ports in NEEDS:
        st = standing(policy, app, ports, cat, live)
        if st == "open":
            continue
        if st == "limited":
            limited.append(app)
            continue
        if st == "off" or (app == "mdns" and "sunshine" in off):
            off.append(app)                              # (remote desktop off: open nothing for it)
            continue
        policy = add_allow(policy, app, name)
        added.append(app)
    if "sunshine" in off:
        # nothing is changed: the other device explains it, and this one shows who tried (starchaser link)
        return {"ok": True, "changed": False, "why": "turned off in the firewall", "off": off, "limited": limited}
    if "sunshine" in limited:
        # allowed only for some devices: the paired device may be one of them, so it can still try
        return {"ok": True, "changed": False, "why": "limited to certain devices or ports in the firewall", "off": off,
                "limited": limited}
    if not added:
        return {"ok": True, "changed": False, "why": "already allowed", "off": off, "limited": limited}
    try:
        clean = fw.validate(policy)
    except fw.PolicyError as e:
        return {"ok": False, "errors": str(e)}
    # A change waiting for Keep: the policy its countdown (or a restart) would go back to gets the same opening,
    # judged by its own rules, so remote desktop isn't cut off then; the waiting change itself stays unconfirmed.
    w = adm.waiting()
    old_w = json.loads(json.dumps(w)) if w else None
    if w and w["prev"].get("enabled"):
        try:
            prev = fw.validate(w["prev"])
            folded = False
            for app, name, ports in NEEDS:
                if app in added and standing(prev, app, ports, cat, live) == "none":
                    prev, folded = add_allow(prev, app, name), True
            if folded:
                w["prev"] = fw.validate(prev)
                w["prevNft"] = None                      # compiled again if a restart has to put it back
                w["prevMissing"] = False
                adm.save_waiting(w)
        except fw.PolicyError:
            pass                                         # leave the way back as it was
    err = firewall_access.load(fw, adm, clean,
                               "A computer in your fleet allowed remote desktop on your fleet's networks" if "sunshine" in added
                               else "A paired device allowed finding devices on your fleet's networks", w, old_w)
    if err:
        return {"ok": False, "errors": err}
    had, now = {x.get("id") for x in before}, {r["id"] for r in clean["rules"]}
    record([i for i in recorded() if i in now] + sorted(now - had))
    return {"ok": True, "changed": True, "added": added, "off": off, "limited": limited}


def wake_on_lan() -> dict:
    """Magic-packet wake on for every wired connection that doesn't have it yet; which ones changed."""
    out = subprocess.run(["nmcli", "-t", "-f", "UUID,TYPE,DEVICE", "connection", "show"], capture_output=True, text=True).stdout
    wired, changed, previous = [], [], {}
    for line in out.splitlines():
        uuid, typ, dev = (line.split(":") + ["", "", ""])[:3]
        if typ != "802-3-ethernet":
            continue
        wired.append(dev or uuid)
        now = subprocess.run(["nmcli", "-g", "802-3-ethernet.wake-on-lan", "connection", "show", uuid],
                             capture_output=True, text=True).stdout.strip()
        if now == "magic":
            continue
        if subprocess.run(["nmcli", "connection", "modify", uuid, "802-3-ethernet.wake-on-lan", "magic"],
                          capture_output=True).returncode != 0:
            continue
        # NetworkManager sets it on the card the next time the connection comes up; ethtool (when it's installed,
        # which Starchaser doesn't need) sets it right now too
        if dev and shutil.which("ethtool"):
            try:
                subprocess.run(["ethtool", "-s", dev, "wol", "g"], capture_output=True, timeout=10)
            except (OSError, subprocess.TimeoutExpired):
                pass
        changed.append(dev or uuid)
        previous[uuid] = now or "default"                # what Undo puts back
    return {"ok": True, "wired": wired, "changed": changed, "previous": previous}


WOL_VALUES = ("default", "ignore", "none", "phy", "unicast", "multicast", "broadcast", "arp", "magic")


def _wol_value(value: str):
    """A value nmcli printed (a name, several names, or a number) in a form safe to hand back, or None."""
    if re.fullmatch(r"[0-9]{1,10}", value):
        return value
    names = [n for n in re.split(r"[,\s]+", value) if n]
    if names and all(n in WOL_VALUES for n in names):
        return ",".join(names)
    return None


def undo_wake_on_lan(pairs: list) -> dict:
    """Put back what wake_on_lan() changed: each pair is "<connection uuid>=<the value it had>" (its "previous")."""
    undone = []
    for pair in pairs:
        uuid, _, value = pair.partition("=")
        value = _wol_value(value)
        if not re.fullmatch(r"[0-9a-fA-F-]{8,40}", uuid) or value is None:
            continue                                     # only a connection id and a value NetworkManager knows
        if subprocess.run(["nmcli", "connection", "modify", uuid, "802-3-ethernet.wake-on-lan", value],
                          capture_output=True).returncode == 0:
            undone.append(uuid)
    return {"ok": True, "undone": undone}


if __name__ == "__main__":
    if any(a in ("-h", "--help") for a in sys.argv[1:]) or sys.argv[1:] == ["help"]:
        print(__doc__.strip())
        sys.exit(0)
    if os.geteuid() != 0:
        print(json.dumps({"ok": False, "errors": "run through pkexec"}))
        sys.exit(1)
    if sys.argv[1:] == ["wake-on-lan"]:
        print(json.dumps(wake_on_lan()))
        sys.exit(0)
    if sys.argv[1:2] == ["undo-wake-on-lan"]:
        print(json.dumps(undo_wake_on_lan(sys.argv[2:])))
        sys.exit(0)
    if sys.argv[1:] in (["allow"], ["disallow"]):
        res = allow() if sys.argv[1] == "allow" else disallow()
        print(json.dumps(res))
        sys.exit(0 if res.get("ok") else 1)
    # a newer starchaser link asking an older copy of this helper: a short answer, not the usage text
    print(json.dumps({"ok": False, "errors": "unknown request", "unknown": True}))
    sys.exit(2)
