#!/usr/bin/python3 -I
"""The screens' one door to `starchaser fleet` (fleet v2 build phase 7; docs/fleet/commands.md, rules 33 and 34).

Every screen action of Mission Control > Your fleet, People, Computers, Activity and Advanced, of Settings > Fleet,
of Welcome's Join a fleet, of the sign-in and lock screens and of the bell is one row of ACTIONS below: its id, the
screen action as commands.md names it, and the one command form it runs. A screen calls

    starchaser-fleet-screen ACTION-ID ARG...

where ARG... is the command line after `starchaser fleet`. This helper checks the arguments match that action's one
form and refuses anything else (rule 33.3: each screen action calls its one command and nothing more), then runs the
command in a pseudo-terminal of its own, so a password or a code is typed where a person types it and never passed
in an argument, a file or the environment (commands.md "Fleet admin", rule 11.1). The command, not this helper,
talks to the fleet service (rule 33.1, 33.7); the screens never write fleet files.

What the screen sees, one JSON object per line on standard output:
    {"out": "a line the command printed"}          the command's own words: the screens show them as printed,
                                                   so a refusal has one message on both front ends (rule 33.3)
    {"ask": "Fleet admin password for dana ...: ", "secret": true}
                                                   the command is waiting for a line; "secret" when it turned the
                                                   terminal's echo off (a password or a code)
    {"exit": 0}                                    the command's exit code (commands.md: 0 done, 1 failed,
                                                   2 wrong usage, 3 refused by a rule, 4 waiting, 5 no terminal)
and it answers each "ask" with one line on standard input. Closing standard input ends the command (Cancel, or the
sheet's close x); a change is only made after its last answer, so nothing changed.

Root-here actions (rule 33.2) are run by the screens through pkexec with the action id as the first argument, so
polkit shows the message of org.starchaser.fleet.ACTION-ID that names the change
(/usr/share/polkit-1/actions/org.starchaser.fleet-screen.policy). The person behind pkexec is the caller the
command asks the password of.

    starchaser-fleet-screen --actions        prints ACTIONS as JSON (for tests and the screens' own checks)
"""
import errno
import json
import os
import pty
import pwd
import re
import select
import signal
import sys
import termios
import time

# One row per screen action (commands.md, in its order). "form" is the command form exactly as commands.md writes
# it; "root" marks Root here (pkexec, rule 33.2); "fronts" names the screens that call it (the map test checks each
# names this id). Build phase 8 added its three: Make backup flagship, Stop being the backup, Take over as flagship.
ACTIONS = [
    # The fleet itself
    {"id": "start", "form": "start [--name NAME] [--range FIRST-LAST] [--trust-network]", "root": True,
     "screen": "Mission Control > Your fleet > Turn on", "fronts": ["mc"]},
    {"id": "status", "form": "status", "screen": "Settings > Fleet (the summary at the top)",
     "fronts": ["mc", "settings"]},
    {"id": "sync", "form": "sync", "screen": "Settings > Fleet > Check now", "fronts": ["settings"]},
    {"id": "doctor", "form": "doctor", "screen": "Settings > Fleet > Troubleshoot", "fronts": ["settings"]},
    {"id": "log", "form": "log [--follow] [--person PERSON] [--computer COMPUTER]", "screen": "Mission Control > Activity",
     "fronts": ["mc"]},
    {"id": "log-journal", "form": "log journal on|off", "screen": "Activity > Also write to the system log",
     "fronts": ["mc"]},
    {"id": "recovery-code-new", "form": "recovery-code new", "screen": "Your fleet > Get a new recovery code",
     "fronts": ["mc"]},
    {"id": "recover", "form": "recover", "root": True,
     "screen": "Sign-in screen > Forgot password > Use your fleet recovery code; Settings > Fleet > Use fleet "
               "recovery code", "fronts": ["settings", "greeter"]},
    {"id": "new-key", "form": "new-key", "screen": "Your fleet > Advanced > Make a new fleet key", "fronts": ["mc"]},
    {"id": "rekey", "form": "rekey FINGERPRINT", "root": True,
     "screen": "Settings > Fleet > Move this computer to the new key", "fronts": ["settings"]},
    {"id": "finish", "form": "finish", "screen": "The bell's Finish (it opens Settings > Fleet, where Finish runs)",
     "fronts": ["bell", "settings"]},
    # Computers
    {"id": "list-computers", "form": "list computers", "screen": "Mission Control > Computers", "fronts": ["mc"]},
    {"id": "join", "form": "join [--via ADDRESS] [--trust-network]", "root": True,
     "screen": "Welcome > Join a fleet; Settings > Fleet > Join a fleet", "fronts": ["settings", "welcome"]},
    {"id": "join-token", "form": "join --token [--via ADDRESS] [--name NAME] [--trust-network]", "root": True,
     "screen": "Welcome > Join a fleet > I have a join token", "fronts": ["welcome"]},
    {"id": "join-token-file",
     "form": "join --token-file FILE [--via ADDRESS] [--name NAME] [--trust-network] [--at-next-start]", "root": True,
     "screen": "Welcome > Join a fleet > I have a join token > Use a file", "fronts": ["welcome"]},
    {"id": "join-paired", "form": "join --paired COMPUTER", "root": True,
     "screen": "Settings > Fleet > \"Den-PC invites this computer to your fleet\" > Join", "fronts": ["settings"]},
    {"id": "admit",
     "form": "admit CODE [--person PERSON]... [--admin PERSON]... [--tag TAG]... [--key PERSON:FINGERPRINT]... "
             "[--replaces COMPUTER]",
     "screen": "Computers > \"Kitchen-Laptop wants to join\" > type the code > Allow", "fronts": ["mc"]},
    {"id": "deny", "form": "deny COMPUTER", "screen": "Computers > \"Kitchen-Laptop wants to join\" > Deny",
     "fronts": ["mc"]},
    {"id": "computer-add", "form": "computer add NAME --address ADDRESS",
     "screen": "Computers > Add a computer > Another computer that can't join", "fronts": ["mc"]},
    {"id": "installer", "form": "installer",
     "screen": "Computers > Add a computer > A Linux computer that isn't Starchaser > Copy the installer",
     "fronts": ["mc"]},
    {"id": "installer-mac", "form": "installer --mac",
     "screen": "Computers > Add a computer > A Mac > Copy the installer", "fronts": ["mc"]},
    {"id": "admit-paired", "form": "admit --paired COMPUTER [--person PERSON]... [--admin PERSON]... [--tag TAG]...",
     "screen": "Computers > \"Kitchen-Laptop is paired but not in your fleet yet\" > Invite", "fronts": ["mc"]},
    {"id": "token-new",
     "form": "token new [--tag TAG]... [--person PERSON]... [--uses N] [--expires DURATION] [--name-prefix PREFIX] "
             "[--replaces COMPUTER]",
     "screen": "Advanced > Join tokens > Make a join token", "fronts": ["mc"]},
    {"id": "list-tokens", "form": "list tokens", "screen": "Advanced > Join tokens", "fronts": ["mc"]},
    {"id": "token-revoke", "form": "token revoke TOKEN-ID", "screen": "Join tokens > token > Revoke",
     "fronts": ["mc"]},
    {"id": "computer-rename", "form": "computer rename COMPUTER NEW-NAME", "screen": "Computers > computer > Rename",
     "fronts": ["mc"]},
    {"id": "computer-tag", "form": "computer tag COMPUTER TAG", "screen": "Computers > computer > Advanced > Tags > Add",
     "fronts": ["mc"]},
    {"id": "computer-untag", "form": "computer untag COMPUTER TAG",
     "screen": "Computers > computer > Advanced > Tags > tag > Remove", "fronts": ["mc"]},
    {"id": "computer-lost", "form": "computer lost COMPUTER [--keep-keys]",
     "screen": "Computers > computer > Lost or stolen > Mark as lost", "fronts": ["mc"]},
    {"id": "computer-remove", "form": "computer remove COMPUTER", "screen": "Computers > computer > Remove from fleet",
     "fronts": ["mc"]},
    {"id": "computer-needs-reset", "form": "computer needs-reset COMPUTER",
     "screen": "Computers > computer > Mark as needing a reset", "fronts": ["mc"]},
    {"id": "reset", "form": "reset", "root": True,
     "screen": "Settings > Fleet > \"This computer needs a reset\" > Reset this computer", "fronts": ["settings"]},
    {"id": "sell", "form": "sell", "root": True, "screen": "Settings > Fleet > Prepare to sell or give away",
     "fronts": ["settings"]},
    {"id": "leave", "form": "leave [--anyway]", "root": True, "screen": "Settings > Fleet > Leave your fleet",
     "fronts": ["settings"]},
    {"id": "flagship-backup", "form": "flagship backup COMPUTER", "screen": "Computers > computer > Make backup flagship",
     "fronts": ["mc"]},
    {"id": "flagship-backup-none", "form": "flagship backup --none",
     "screen": "Computers > backup > Stop being the backup", "fronts": ["mc"]},
    {"id": "flagship-take-over", "form": "flagship take-over", "root": True,
     "screen": "Settings > Fleet (on the backup) > Take over as flagship", "fronts": ["settings"]},
    # People
    {"id": "list-people", "form": "list people", "screen": "Mission Control > People", "fronts": ["mc"]},
    {"id": "person-new",
     "form": "person new PERSON --name \"FULL NAME\" [--fleet-admin] [--on COMPUTER]... [--admin-on COMPUTER]... "
             "[--group GROUP]...",
     "screen": "People > Add a person > Add", "fronts": ["mc"]},
    {"id": "person-edit", "form": "person edit PERSON --name \"FULL NAME\"", "screen": "People > person > Edit name",
     "fronts": ["mc"]},
    {"id": "person-role", "form": "person role PERSON fleet-admin|standard",
     "screen": "People > person > Fleet admin switch", "fronts": ["mc"]},
    {"id": "person-remove", "form": "person remove PERSON [--files-to PERSON | --keep-files] [--untrusted]",
     "screen": "People > person > Remove", "fronts": ["mc"]},
    {"id": "person-restore", "form": "person restore PERSON", "screen": "People > Removed > person > Restore",
     "fronts": ["mc"]},
    {"id": "password-change", "form": "password change",
     "screen": "Settings > Users > Change password; the lock screen's Change password", "fronts": ["settings", "lock"]},
    {"id": "password-reset", "form": "password reset PERSON", "screen": "People > person > Reset password",
     "fronts": ["mc"]},
    {"id": "password-finish", "form": "password finish",
     "screen": "Settings > Fleet > \"Changed only on this computer\" > Finish on all computers",
     "fronts": ["settings"]},
    # Rules, groups, tags and service accounts
    {"id": "list-rules", "form": "list rules", "screen": "Mission Control > Advanced > Rules", "fronts": ["mc"]},
    {"id": "allow-signin", "form": "allow PERSON --on COMPUTER --signin", "screen": "People > person > tick a computer",
     "fronts": ["mc"]},
    {"id": "allow-sudo", "form": "allow PERSON --on COMPUTER --sudo",
     "screen": "People > person > check Admin on this computer only", "fronts": ["mc"]},
    {"id": "disallow-signin", "form": "disallow PERSON --on COMPUTER --signin",
     "screen": "People > person > untick the computer", "fronts": ["mc"]},
    {"id": "disallow-sudo", "form": "disallow PERSON --on COMPUTER --sudo",
     "screen": "People > person > uncheck Admin on this computer only", "fronts": ["mc"]},
    {"id": "rule-add", "form": "allow WHO --on WHERE --signin|--sudo", "screen": "Rules > Add a rule",
     "fronts": ["mc"]},
    {"id": "rule-remove", "form": "disallow WHO --on WHERE --signin|--sudo", "screen": "Rules > rule > Remove",
     "fronts": ["mc"]},
    {"id": "list-groups", "form": "list groups", "screen": "Mission Control > Advanced > Groups", "fronts": ["mc"]},
    {"id": "group-new", "form": "group new GROUP [--name \"DISPLAY NAME\"]", "screen": "Groups > New group",
     "fronts": ["mc"]},
    {"id": "group-delete", "form": "group delete GROUP", "screen": "Groups > group > Delete group", "fronts": ["mc"]},
    {"id": "group-add", "form": "group add GROUP PERSON", "screen": "Groups > group > Add a member", "fronts": ["mc"]},
    {"id": "group-remove", "form": "group remove GROUP PERSON", "screen": "Groups > group > member > Remove from group",
     "fronts": ["mc"]},
    {"id": "list-services", "form": "list services", "screen": "Mission Control > Advanced > Service accounts",
     "fronts": ["mc"]},
    {"id": "service-new", "form": "service new NAME [--group GROUP]...",
     "screen": "Service accounts > New service account", "fronts": ["mc"]},
    {"id": "service-remove", "form": "service remove NAME", "screen": "Service accounts > account > Remove",
     "fronts": ["mc"]},
    # SSH keys and host keys
    {"id": "list-keys", "form": "list keys [PERSON]", "screen": "People > person > Advanced > SSH keys",
     "fronts": ["mc"]},
    {"id": "key-add", "form": "key add PERSON KEYFILE [--label LABEL]", "screen": "SSH keys > Add a key",
     "fronts": ["mc"]},
    {"id": "key-remove", "form": "key remove PERSON FINGERPRINT", "screen": "SSH keys > key > Remove",
     "fronts": ["mc"]},
    {"id": "known-hosts", "form": "known-hosts", "screen": "Advanced > Host keys > Copy the list", "fronts": ["mc"]},
    # Accounts on this computer
    {"id": "renumber-preview", "form": "renumber ACCOUNT --preview", "root": True,
     "screen": "Settings > Fleet > \"Sam's account number doesn't match\" > Renumber", "fronts": ["settings"]},
    {"id": "renumber", "form": "renumber ACCOUNT [--to NUMBER] [--yes]", "root": True,
     "screen": "the preview > Renumber Sam", "fronts": ["settings"]},
    {"id": "renumber-end-sessions", "form": "renumber ACCOUNT --end-sessions [--yes]", "root": True,
     "screen": "the preview, when Sam is signed in > Sign out and renumber", "fronts": ["settings"]},
    {"id": "keep-local", "form": "keep-local ACCOUNT", "root": True,
     "screen": "the same row > Keep it on this computer only", "fronts": ["settings"]},
    # Files for other tools
    {"id": "export", "form": "export", "screen": "Advanced > Export fleet file", "fronts": ["mc"]},
    {"id": "export-accounts", "form": "export --accounts", "screen": "Advanced > Accounts for another computer",
     "fronts": ["mc"]},
    {"id": "apply", "form": "apply FILE", "screen": "Advanced > Apply fleet file, then Apply on the preview",
     "fronts": ["mc"]},
    {"id": "apply-check", "form": "apply FILE --check", "screen": "Advanced > Apply fleet file (the preview)",
     "fronts": ["mc"]},
    {"id": "inventory", "form": "list computers --inventory", "screen": "Advanced > Export for automation",
     "fronts": ["mc"]},
]
BY_ID = {a["id"]: a for a in ACTIONS}
PACKAGED = "/usr/bin/starchaser"
QUIET = 0.25           # seconds of silence after a line with no newline: the command is waiting for an answer
LITERAL = re.compile(r"^[a-z][a-z-]*(\|[a-z][a-z-]*)*$")


def tokens(form: str) -> list:
    """The form's parts: ("word", choices) for a verb word, ("arg", NAME) for an argument, ("opt", [alternatives],
    takes_value, required, many) for an option or a group of alternatives."""
    out = []
    parts = re.findall(r'\[[^\]]*\](?:\.\.\.)?|"[^"]*"|\S+', form)
    for p in parts:
        many = p.endswith("...")
        if many:
            p = p[:-3]
        if p.startswith("[") and not p.startswith("[-"):
            out.append(("optarg", p[1:-1]))                  # "list keys [PERSON]"
        elif p.startswith("["):
            inner = p[1:-1]
            alts = []
            for alt in inner.split(" | ") if " | " in inner else [inner]:
                bits = alt.split(None, 1)
                alts.append((bits[0], len(bits) > 1))
            out.append(("opt", alts, False, many))
        elif p.startswith("--"):
            alts = [(a, False) for a in p.split("|")]
            out.append(("req", alts))
        elif LITERAL.match(p):
            out.append(("word", p.split("|")))
        else:
            out.append(("arg", p))
    # a required option with a value ("--name \"FULL NAME\"", "--address ADDRESS", "--token-file FILE",
    # "--paired COMPUTER", "--on COMPUTER") is a "req" followed by its "arg": fold them
    folded, i = [], 0
    while i < len(out):
        t = out[i]
        if t[0] == "req" and len(t[1]) == 1 and i + 1 < len(out) and out[i + 1][0] == "arg":
            folded.append(("req", [(t[1][0][0], True)]))
            i += 2
            continue
        folded.append(t)
        i += 1
    return folded


def matches(form: str, args: list) -> bool:
    """Do these arguments (after `starchaser fleet`) fit this one form? `--json` fits every form (commands.md)."""
    args = [a for a in args if a != "--json"]
    toks = tokens(form)
    fixed = [t for t in toks if t[0] in ("word", "arg")]
    req = [t for t in toks if t[0] == "req"]
    opts = [t for t in toks if t[0] == "opt"]
    positional, seen, i = [], {}, 0
    valued = {name: v for t in req + opts for name, v in t[1]}
    while i < len(args):
        a = args[i]
        if a.startswith("--") and a != "--":
            name, eq, inline = a.partition("=")
            if name not in valued:
                return False
            if valued[name]:
                if not eq:
                    i += 1
                    if i >= len(args):
                        return False
                    inline = args[i]
                if not inline:
                    return False
            elif eq:
                return False
            seen[name] = seen.get(name, 0) + 1
        else:
            positional.append(a)
        i += 1
    optional = sum(1 for t in toks if t[0] == "optarg")
    if not len(fixed) <= len(positional) <= len(fixed) + optional:
        return False
    for t, a in zip(fixed + [("arg", "")] * optional, positional):
        if t[0] == "word" and a not in t[1]:
            return False
        if t[0] == "arg" and (not a or (a.startswith("-") and a != "-")):
            return False
    for t in req:
        if sum(seen.get(n, 0) for n, _ in t[1]) != 1:
            return False
    for t in opts:
        count = sum(seen.get(n, 0) for n, _ in t[1])
        if count > 1 and not t[3]:
            return False
        if len({n for n, _ in t[1] if seen.get(n)}) > 1:
            return False                         # "[--files-to PERSON | --keep-files]": one or the other
    return True


def command() -> str:
    """The `starchaser` command to run: the package's /usr/bin/starchaser, or on a computer set up from a checkout
    the account's own ~/.local/bin/starchaser (as root through pkexec, the account behind it: the same command that
    account runs with sudo)."""
    if os.environ.get("STARCHASER_FLEET_SCREEN_COMMAND"):
        return os.environ["STARCHASER_FLEET_SCREEN_COMMAND"]
    if os.path.exists(PACKAGED):
        return PACKAGED
    uid = os.environ.get("PKEXEC_UID") or os.environ.get("SUDO_UID") or str(os.getuid())
    try:
        own = os.path.join(pwd.getpwuid(int(uid)).pw_dir, ".local/bin/starchaser")
    except (KeyError, ValueError):
        own = ""
    return own if own and os.path.exists(own) else PACKAGED


def emit(obj: dict) -> None:
    sys.stdout.write(json.dumps(obj) + "\n")
    sys.stdout.flush()


def child_env() -> dict:
    env = dict(os.environ)
    env.pop("STARCHASER_FLEET_SCREEN_COMMAND", None)
    env["TERM"] = "dumb"
    env["LC_ALL"] = env.get("LC_ALL") or "C.UTF-8"
    # pkexec (rule 33.2): the person behind it is the caller the command asks for, as sudo's SUDO_USER is
    uid = os.environ.get("PKEXEC_UID")
    if os.geteuid() == 0 and uid and uid.isdigit() and not env.get("SUDO_USER"):
        try:
            env["SUDO_USER"] = pwd.getpwuid(int(uid)).pw_name
            env["SUDO_UID"] = uid
        except KeyError:
            pass
    return env


def echo_off(fd: int) -> bool:
    try:
        return not termios.tcgetattr(fd)[3] & termios.ECHO
    except termios.error:
        return False


def run(args: list) -> tuple:
    cmd = command()
    pid, fd = pty.fork()
    if pid == 0:                                 # the command, on its own terminal
        try:
            os.execve(cmd, [cmd, "fleet", *args], child_env())
        finally:
            os._exit(127)
    buf, echo, last, asked = "", None, time.monotonic(), False
    stdin_open, canceled, stop_at = True, False, 0

    def lines(text: str) -> None:
        nonlocal buf, echo
        buf += text.replace("\r", "")
        while "\n" in buf:
            line, buf = buf.split("\n", 1)
            if echo is not None and line == echo:            # the terminal's echo of an answer just sent
                echo = None
                continue
            echo = None
            emit({"out": line})

    while True:
        watch = [fd] + ([sys.stdin.fileno()] if stdin_open else [])
        if stop_at and time.monotonic() >= stop_at:
            with_kill(pid)
            stop_at = 0
        try:
            ready, _, _ = select.select(watch, [], [], QUIET)
        except InterruptedError:
            continue
        if fd in ready:
            try:
                data = os.read(fd, 65536)
            except OSError as e:
                if e.errno != errno.EIO:
                    raise
                data = b""
            if not data:
                break
            lines(data.decode("utf-8", "replace"))
            last, asked = time.monotonic(), False
            continue
        if sys.stdin.fileno() in ready:
            answer = sys.stdin.readline()
            if not answer:                                   # the sheet was closed (Cancel, the close x)
                stdin_open, canceled = False, True
                interrupt(pid)                               # as Ctrl+C: join says "Nothing changed." and stops
                stop_at = time.monotonic() + 3
                continue
            if not asked:                                    # a line nobody asked for is not typed anywhere
                continue
            answer = answer.rstrip("\n")
            secret = echo_off(fd)
            os.write(fd, (answer + "\n").encode())
            echo = None if secret else answer
            buf = ""                                         # the prompt was shown as "ask"; the echo follows
            asked = False
            continue
        if buf and not asked and time.monotonic() - last >= QUIET:
            emit({"ask": buf, "secret": echo_off(fd)})
            asked = True
            if not stdin_open:
                canceled = True
                with_kill(pid)
    if buf and not canceled:
        emit({"out": buf})
    _, status = os.waitpid(pid, 0)
    code = os.waitstatus_to_exitcode(status)
    return (1 if code < 0 else code), canceled


def interrupt(pid: int) -> None:
    try:
        os.kill(pid, signal.SIGINT)
    except ProcessLookupError:
        pass


def with_kill(pid: int) -> None:
    try:
        os.kill(pid, signal.SIGTERM)
    except ProcessLookupError:
        pass


def main(argv: list) -> int:
    if argv[:1] == ["--actions"]:
        print(json.dumps(ACTIONS))
        return 0
    if not argv or argv[0] not in BY_ID:
        print("Usage: starchaser-fleet-screen ACTION-ID ARG...", file=sys.stderr)
        return 2
    action, args = BY_ID[argv[0]], argv[1:]
    if not matches(action["form"], args):
        emit({"out": f"That isn't what {action['screen']} runs. Nothing changed."})
        emit({"exit": 2})
        return 2
    if action.get("root") and os.geteuid() != 0 and not os.environ.get("STARCHASER_FLEET_RUN"):
        emit({"out": "This change needs an administrator of this computer. Nothing changed."})
        emit({"exit": 3})
        return 3
    code, canceled = run(args)
    emit({"exit": code, "canceled": True} if canceled else {"exit": code})
    return 0


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