#!/usr/bin/env python3
"""Serve Tailcat SSH or forward to an existing SSH server, then print a browser link."""

import argparse
import base64
import getpass
import hashlib
import json
import os
from pathlib import Path
import re
import signal
import struct
import subprocess
import sys
import tempfile
from urllib.parse import urlencode, urlsplit, urlunsplit


DEFAULT_SITE = "https://tailcat-browser-console.vercel.app/"
ADDRESS = re.compile(r"tc[A-Za-z0-9_-]{1,8190}")
ED25519_SPKI = bytes.fromhex("302a300506032b6570032100")


def config_directory():
    if os.name == "nt":
        return Path(os.environ["APPDATA"])
    if sys.platform == "darwin":
        return Path.home() / "Library" / "Application Support"
    return Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config")


def ssh_host_fingerprint():
    key_path = config_directory() / "tailcat" / "ssh" / "ssh_host_ed25519_key"
    if not key_path.exists():
        key_path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
        with tempfile.TemporaryDirectory(dir=key_path.parent) as work:
            generated = Path(work) / "host-key"
            subprocess.run(
                ["openssl", "genpkey", "-algorithm", "ED25519", "-out", str(generated)],
                check=True,
            )
            generated.chmod(0o600)
            try:
                # Publish the complete key atomically without replacing an existing key.
                os.link(generated, key_path)
            except FileExistsError:
                pass

    public = subprocess.check_output(
        ["openssl", "pkey", "-in", str(key_path), "-pubout", "-outform", "DER"]
    )
    if not public.startswith(ED25519_SPKI) or len(public) != len(ED25519_SPKI) + 32:
        raise ValueError("Tailcat host key is not in the expected Ed25519 format")
    fields = [b"ssh-ed25519", public[len(ED25519_SPKI):]]
    blob = b"".join(struct.pack(">I", len(field)) + field for field in fields)
    return fingerprint_of(blob)


def fingerprint_of(blob):
    digest = base64.b64encode(hashlib.sha256(blob).digest()).decode("ascii")
    return "SHA256:" + digest.rstrip("=")


def existing_host_fingerprint(path):
    fields = path.read_bytes().split()
    if len(fields) < 2 or fields[0] != b"ssh-ed25519":
        raise ValueError("specify the existing SSH server's Ed25519 host public key (.pub)")
    blob = base64.b64decode(fields[1], validate=True)
    if len(blob) != 51 or not blob.startswith(b"\0\0\0\x0bssh-ed25519\0\0\0\x20"):
        raise ValueError("the SSH host public key is malformed")
    return fingerprint_of(blob)


def ssh_port(value):
    port = int(value)
    if not 1 <= port <= 65535:
        raise argparse.ArgumentTypeError("SSH port must be between 1 and 65535")
    return port


def https_site(value):
    try:
        site = urlsplit(value)
        valid = (
            site.scheme == "https"
            and site.hostname
            and site.username is None
            and site.password is None
            and site.port != 0
            and not site.query
            and not site.fragment
            and not any(char.isspace() or char == "\\" for char in value)
        )
    except ValueError:
        valid = False
    if not valid:
        raise argparse.ArgumentTypeError("use an HTTPS console URL without credentials, a query or a fragment")
    return site


def current_user():
    if os.name == "nt":
        return getpass.getuser()
    import pwd

    return pwd.getpwuid(os.geteuid()).pw_name


def run_server(args, fingerprint):
    command = [
        "tailcat",
        "--json",
        "serve",
        "--full-address",
    ]
    if args.key:
        command.append("--key=" + args.key)
    if args.allow:
        command.append("--allow=" + args.allow)
    if args.ssh_port:
        command.append(f"{args.ssh_port}:127.0.0.1:{args.ssh_port}")
    else:
        authorized = args.authorized_keys or str(Path.home() / ".ssh" / "authorized_keys")
        command.extend(["--ssh-authorized-keys=" + authorized, "ssh"])
    server = subprocess.Popen(command, stdout=subprocess.PIPE, text=True, encoding="utf-8")
    try:
        line = server.stdout.readline()
        if not line:
            return server.wait() or 1
        profile = json.loads(line)
        address = profile.get("listenAddr") if isinstance(profile, dict) else None
        if not isinstance(address, str) or not ADDRESS.fullmatch(address):
            raise ValueError("Tailcat did not emit a valid address")
        fragment = urlencode({
            "tc": address,
            "u": args.user or current_user(),
            "p": args.ssh_port or 22,
            "fp": fingerprint,
            "m": "password" if args.ssh_port else "key",
        })
        print(urlunsplit(args.site._replace(path=args.site.path or "/", fragment=fragment)), flush=True)
        return server.wait()
    finally:
        if server.poll() is None:
            server.terminate()
            try:
                server.wait(timeout=5)
            except subprocess.TimeoutExpired:
                server.kill()
                server.wait()
        server.stdout.close()


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--site", default=DEFAULT_SITE, type=https_site, help="HTTPS URL of your console")
    parser.add_argument(
        "--authorized-keys",
        help="Tailcat SSH authorized public key sources",
    )
    parser.add_argument("--key", help="optional saved Tailcat server key name or path")
    parser.add_argument("--allow", help="optional Tailcat client node public keys")
    parser.add_argument("--ssh-port", type=ssh_port, help="forward to an existing SSH listener on 127.0.0.1")
    parser.add_argument("--host-public-key", type=Path, help="that listener's Ed25519 host public key")
    parser.add_argument("--user", help="SSH username to fill in the browser link")
    args = parser.parse_args()
    if bool(args.ssh_port) != bool(args.host_public_key):
        parser.error("--ssh-port and --host-public-key must be specified together")
    if args.ssh_port and args.authorized_keys:
        parser.error("--authorized-keys applies to Tailcat's built-in SSH service")
    if args.user is not None and (not args.user.strip() or len(args.user) > 128):
        parser.error("--user must contain 1 to 128 characters")

    def terminate(_signum, _frame):
        raise SystemExit(143)

    signal.signal(signal.SIGTERM, terminate)
    try:
        fingerprint = (
            existing_host_fingerprint(args.host_public_key)
            if args.ssh_port else ssh_host_fingerprint()
        )
        return run_server(args, fingerprint)
    except KeyboardInterrupt:
        return 130
    except FileNotFoundError as error:
        print(f"Missing executable or file: {error.filename}", file=sys.stderr)
    except json.JSONDecodeError:
        print("Tailcat did not emit a JSON startup record", file=sys.stderr)
    except (OSError, subprocess.SubprocessError, ValueError) as error:
        print(f"Could not start Tailcat Console: {error}", file=sys.stderr)
    return 1


if __name__ == "__main__":
    sys.exit(main())
