#!/usr/bin/env python3
"""starchaser: on a Linux computer that isn't Starchaser, or on a Mac, the fleet's commands and nothing else (rules
35.7 and 35.10).

The install script (`starchaser fleet installer`, printed by any fleet computer) links /usr/local/bin/starchaser to
this file. `starchaser fleet ...` here is the same program a Starchaser computer runs (starchaser_fleet_v2.py beside
this file, asking this computer's own fleet service), so every command, message and exit code in
docs/fleet/commands.md is the same. This computer has no Settings or Mission Control: what those screens do on a
Starchaser computer, these commands do here and the flagship's screens do from there.
"""
import json
import os
import shutil
import subprocess
import sys
from pathlib import Path

LIB = Path(__file__).resolve().parent
sys.path.insert(0, str(LIB))
import starchaser_fleet_v2 as v2  # noqa: E402

ONLY = ("This computer has Starchaser's fleet software only. Its commands start with: starchaser fleet\n"
        "Run 'starchaser fleet' for the list.")
MARKER = Path("/etc/starchaser/fleet-member.json")
SSHD_UNITS = ("sshd.service", "ssh.service", "ssh.socket", "sshd.socket")
MAC = sys.platform == "darwin"                     # a Mac member (rules 35.10 to 35.12): launchd, Remote Login


def overview() -> int:
    print("Usage: starchaser fleet COMMAND ...\n\nYour fleet's commands on this computer. This computer isn't "
          "Starchaser, so everything is done here on the\ncommand line, or from your flagship's screens.\n")
    for verb in v2.VERBS:
        if verb in v2.HELP:
            for line in v2.HELP[verb][0].splitlines():
                print("  " + line.strip())
    print("  starchaser fleet doctor\n\nRun 'starchaser fleet COMMAND --help' for one command.")
    return v2.DONE


def active(unit: str) -> bool:
    return subprocess.run(["systemctl", "is-active", "--quiet", unit], check=False).returncode == 0


def loaded(label: str) -> bool:
    """Whether launchd holds a job of that name (a Mac)."""
    return subprocess.run(["/bin/launchctl", "print", "system/" + label], capture_output=True,
                          check=False).returncode == 0


def mac_doctor(line) -> None:
    """Rule 35.9's Troubleshoot on a Mac: the same questions, asked of launchd and Remote Login."""
    line(all((v2.run_dir() / n).exists() for n in ("root.sock", "people.sock")) and loaded("com.starchaser.fleet"),
         "The fleet service is ready.",
         "The fleet service isn't running. Run: sudo launchctl bootstrap system "
         "/Library/LaunchDaemons/com.starchaser.fleet.plist")
    line(loaded("com.openssh.sshd"), "Remote Login is on (the fleet link and fleet SSH keys use it).",
         "Remote Login is off, so your fleet can't reach this Mac and fleet SSH keys have nothing to open. Turn it on "
         "in System Settings > General > Sharing > Remote Login. This Mac still asks your fleet for news by itself.")
    if os.geteuid() == 0 and Path("/etc/ssh/sshd_config.d/00-starchaser-fleet-keys.conf").exists():
        r = subprocess.run(["/usr/sbin/sshd", "-T"], capture_output=True, text=True, check=False)
        cfg = r.stdout.lower()
        line("/etc/starchaser/fleet/ssh/authorized_keys/%u" in cfg and "revokedkeys /etc/starchaser/fleet/ssh" in cfg,
             "sshd uses the fleet's SSH keys and its revoked key list.",
             "sshd isn't using the fleet's key files. Check that /etc/ssh/sshd_config has the line: "
             "Include /etc/ssh/sshd_config.d/*")
    elif os.geteuid() != 0:
        print("      Run this with sudo to also check sshd's settings.")
    print("      A Mac follows your fleet and can't be its flagship or backup. An account that was on this Mac before "
          "it joined\n      keeps its Mac password until its person runs: starchaser fleet password finish")


def doctor() -> int:
    """`starchaser fleet doctor` (Troubleshoot): what the fleet needs from this computer, checked one by one."""
    try:
        marker = json.loads(MARKER.read_text())
    except (OSError, ValueError):
        marker = {}
    bad = 0

    def line(ok: bool, good: str, fix: str) -> None:
        nonlocal bad
        bad += 0 if ok else 1
        print(("ok    " + good) if ok else ("FIX   " + fix))

    line(bool(marker), f"The fleet software is installed (version {marker.get('version', '?')}).",
         "The fleet software isn't installed whole. Run the installer again (on a fleet computer: starchaser fleet "
         "installer).")
    if MAC:
        mac_doctor(line)
        return doctor_status(bad)
    line(all((v2.run_dir() / n).exists() for n in ("root.sock", "people.sock")), "The fleet service is ready.",
         "The fleet service isn't ready. Run: sudo systemctl enable --now starchaser-fleet-root.socket "
         "starchaser-fleet-people.socket")
    line(active("starchaser-fleet-listen.socket"), "This computer listens for join requests on port 47744.",
         "Port 47744 isn't open here. Run: sudo systemctl enable --now starchaser-fleet-listen.socket")
    line(any(active(u) for u in SSHD_UNITS), "SSH sign-in is on (the fleet link uses it).",
         "SSH sign-in is off, so your fleet can't reach this computer. Turn on its SSH server.")
    loose = [d for d in ("/", "/etc", "/etc/starchaser", "/etc/starchaser/fleet", "/etc/starchaser/fleet/ssh")
             if os.path.isdir(d) and (os.stat(d).st_mode & 0o022 or os.stat(d).st_uid != 0)]
    line(not loose, "sshd will accept the fleet's key files (only root can write the folders above them).",
         "sshd refuses SSH key files under a folder others can write, so fleet SSH keys and the fleet link won't work "
         "here. Run: sudo chmod go-w " + " ".join(loose))
    if os.geteuid() == 0 and Path("/etc/ssh/sshd_config.d/00-starchaser-fleet-keys.conf").exists():
        r = subprocess.run([shutil.which("sshd") or "/usr/sbin/sshd", "-T"], capture_output=True, text=True,
                           check=False)
        cfg = r.stdout.lower()
        line("/etc/starchaser/fleet/ssh/authorized_keys/%u" in cfg and "revokedkeys /etc/starchaser/fleet/ssh" in cfg,
             "sshd uses the fleet's SSH keys and its revoked key list.",
             "sshd isn't using the fleet's key files. Check that /etc/ssh/sshd_config starts with: "
             "Include /etc/ssh/sshd_config.d/*.conf")
    elif os.geteuid() != 0:
        print("      Run this with sudo to also check sshd's settings.")
    if not shutil.which("avahi-browse"):
        # not a fault: a server needs none. It follows its flagship at the address it joined through and wherever
        # the flagship last reached it from (rule 2.4a); only finding a fleet by itself needs the lookup.
        print("      This computer has no local-network lookup, so it can't find a fleet by itself: when joining, "
              "name a fleet\n      computer (sudo starchaser fleet join --via ADDRESS). In a fleet it keeps following "
              "its flagship unless\n      its own address and the flagship's both change at once.")
    return doctor_status(bad)


def doctor_status(bad: int) -> int:
    link = v2.connect(root=False)
    st = {}
    if link:
        try:
            st = link.ask(op="status")
        except OSError:
            st = {}
        finally:
            link.close()
    if st.get("inFleet"):
        for text in v2.status_lines(st):
            print("      " + text)
    else:
        print("      This computer isn't in a fleet. To join: sudo starchaser fleet join")
    return v2.DONE if not bad else v2.FAILED


def main(argv: list) -> int:
    if not argv or argv[0] in ("help", "--help", "-h"):
        print(ONLY)
        return v2.DONE
    if argv[0] != "fleet":
        print(ONLY, file=sys.stderr)
        return v2.USAGE
    rest = argv[1:]
    if not rest or rest[0] in ("help", "--help", "-h"):
        return overview()
    if rest == ["doctor"]:
        return doctor()
    if not v2.handles(rest):
        print(f"starchaser fleet: there is no command '{rest[0]}'. Run 'starchaser fleet' for the list.",
              file=sys.stderr)
        return v2.USAGE
    r = v2.main(rest)
    if r is v2.LEGACY:                             # the pairing-era verbs behind these words exist only on Starchaser
        if rest[0] == "list":
            return v2.usage("list")
        return v2.fail("This computer isn't in a fleet.", v2.REFUSED)
    return r


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