#!/opt/homebrew/bin/python3
"""devname: stable local names for dev servers, so nobody remembers ports.

One Caddy (a launchd agent, label DEVNAME_LABEL) listens on :80/:443 and proxies each name to its port. An unprivileged process can bind a low port only
on the wildcard address (not 127.0.0.1), so every site first aborts any connection whose source is not loopback.
`*.localhost` resolves to loopback on this Mac with no DNS setup (RFC 6761), so the names are local-program-only.

Names (all end in .localhost):
  <project>.localhost                      the project's main site
  <service>.<project>.localhost            a sub-service (tests, desk, board...)
  <name>--<branch>[.<project>].localhost   a branch variant: the branch joins the first label

Agents: never hard-code a port. `devname ensure` is idempotent: it prints the URL if the name exists, otherwise it
allocates a port (17000-17999), registers the name and reloads Caddy. The service must then listen on that port
(`devname ensure foo --format port`).

  devname ensure [project] [--service S] [--branch B|auto] [--port N] [--keep-host] [--format url|port|json]
  devname ls [--json]          devname rm <host>          devname check <host>
  devname render               devname serve              devname doctor        devname agent install|status

The agent also serves the index page devname.localhost: every registered name, live up/down status,
plus /json. It reads names.json per request — no snapshot to stale.

Registry: $DEVNAME_HOME (default ~/.config/devnames)/names.json. https needs the mkcert root CA (`mkcert -install`, once).
"""
import argparse
import concurrent.futures as cf
import contextlib
import datetime
import fcntl
import hashlib
import html
import http.server
import json
import os
import re
import shutil
import signal
import socket
import subprocess
import sys
import threading
import urllib.error
import urllib.request

HOME = os.path.expanduser("~")
CONF = os.environ.get("DEVNAME_HOME") or os.path.join(HOME, ".config", "devnames")
REG = os.path.join(CONF, "names.json")
CADDYFILE = os.path.join(CONF, "Caddyfile")
ADMIN_SOCK = os.path.join(CONF, "admin.sock")
CERT_DIR = os.path.join(CONF, "certs")
CERT, KEY, SANS = (os.path.join(CERT_DIR, n) for n in ("devname.pem", "devname-key.pem", "sans.txt"))
STATE = os.path.join(HOME, ".local", "state", "devname")
LABEL = os.environ.get("DEVNAME_LABEL", "devname")
PLIST = os.path.join(HOME, "Library", "LaunchAgents", LABEL + ".plist")
LOGDIR = os.path.join(HOME, "Library", "Logs", "devname")
POOL = range(17000, 18000)
CADDY = shutil.which("caddy") or "/opt/homebrew/bin/caddy"
MKCERT = shutil.which("mkcert") or "/opt/homebrew/bin/mkcert"
# no JDK keystore here: mkcert's optional Java step exits 1 and would block issuing the cert (found 2026-11-03)
MKCERT_ENV = dict(os.environ, TRUST_STORES="system,nss")
SUFFIX = ".localhost"
INDEX_PORT = 16999  # internal: the index page behind devname.localhost, served by the agent itself
INDEX_HOST = "devname.localhost"
MAIN_BRANCHES = {"main", "master", "HEAD", ""}
NAME_RE = re.compile(r"^[a-z0-9]([a-z0-9-]{0,38}[a-z0-9])?$")


class Err(Exception):
    pass


def slug(text, maxlen=40):
    """DNS-label-safe: lowercase [a-z0-9-], no leading/trailing/double dashes; long ones keep a short hash."""
    s = re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")
    if not s:
        raise Err(f"cannot make a name from {text!r}")
    if len(s) > maxlen:
        s = s[:maxlen - 7].rstrip("-") + "-" + hashlib.sha1(text.encode()).hexdigest()[:6]
    return s


def check_name(kind, value):
    if not NAME_RE.match(value) or "--" in value:
        raise Err(f"{kind} {value!r} must be lowercase letters, digits, single dashes (max 40)")
    return value


def hostname(project, service=None, branch=None):
    def first(name):
        return name if not branch else f"{name}--{slug(branch, 20)}"
    if service:
        return f"{first(service)}.{project}{SUFFIX}"
    return f"{first(project)}{SUFFIX}"


# ---- registry (flock'd, atomic)
@contextlib.contextmanager
def locked():
    os.makedirs(CONF, mode=0o700, exist_ok=True)
    with open(os.path.join(CONF, ".lock"), "w") as fh:
        fcntl.flock(fh, fcntl.LOCK_EX)
        yield


def load():
    try:
        with open(REG) as fh:
            return json.load(fh)
    except FileNotFoundError:
        return {"version": 1, "entries": {}}


def save(reg):
    tmp = REG + ".tmp"
    with open(tmp, "w") as fh:
        json.dump(reg, fh, indent=2, sort_keys=True)
        fh.write("\n")
    os.replace(tmp, REG)


def port_listening(port):
    with socket.socket() as s:
        s.settimeout(0.3)
        return s.connect_ex(("127.0.0.1", port)) == 0


def alloc_port(reg):
    used = {e["port"] for e in reg["entries"].values()}
    for p in POOL:
        if p not in used and not port_listening(p):
            return p
    raise Err("port pool 17000-17999 exhausted")


# ---- caddy
def have_https():
    return os.path.exists(CERT) and os.path.exists(KEY)


def render_caddyfile(reg, https):
    out = [
        "# generated by devname; do not edit (devname render)",
        "{",
        f"\tadmin unix/{ADMIN_SOCK}",
        "\tauto_https off",
        "}",
    ]
    for host in sorted(reg["entries"]):
        e = reg["entries"][host]
        up = f"127.0.0.1:{e['port']}"
        body = site_body(up, e.get("rewrite", True))
        out += [f"http://{host} {{"] + body + ["}"]
        if https:
            out += [f"https://{host} {{", f"\ttls {CERT} {KEY}"] + body + ["}"]
    body = site_body(f"127.0.0.1:{INDEX_PORT}")
    out += [f"http://{INDEX_HOST} {{"] + body + ["}"]
    if https:
        out += [f"https://{INDEX_HOST} {{", f"\ttls {CERT} {KEY}"] + body + ["}"]
    return "\n".join(out) + "\n"


def site_body(up, rewrite=True):
    body = ["\t@notlocal not remote_ip 127.0.0.0/8 ::1", "\tabort @notlocal", f"\treverse_proxy {up} {{"]
    if rewrite:
        body.append(f"\t\theader_up Host {up}")
    body.append("\t}")
    return body


def ensure_cert(reg):
    """One SAN cert over every registered name (wildcards cannot span two labels). Needs the mkcert root CA."""
    names = sorted(set(reg["entries"]) | {INDEX_HOST, "localhost", "127.0.0.1", "::1"})
    root = subprocess.run([MKCERT, "-CAROOT"], capture_output=True, text=True).stdout.strip()
    if not os.path.exists(os.path.join(root, "rootCA.pem")):
        return False
    want = "\n".join(names)
    have = open(SANS).read() if os.path.exists(SANS) else None
    if have != want or not have_https():
        os.makedirs(CERT_DIR, mode=0o700, exist_ok=True)
        r = subprocess.run([MKCERT, "-cert-file", CERT, "-key-file", KEY] + names, capture_output=True, text=True, env=MKCERT_ENV)
        if r.returncode:
            raise Err("mkcert failed: " + r.stderr.strip()[-200:])
        os.chmod(KEY, 0o600)
        with open(SANS, "w") as fh:
            fh.write(want)
    return True


def render(reg, reload=True):
    https = ensure_cert(reg)
    os.makedirs(CONF, mode=0o700, exist_ok=True)
    text = render_caddyfile(reg, https)
    tmp = CADDYFILE + ".tmp"
    with open(tmp, "w") as fh:
        fh.write(text)
    os.replace(tmp, CADDYFILE)
    if not reload:
        return "written"
    if not os.path.exists(ADMIN_SOCK):
        return "written (agent not running: nothing reloaded)"
    r = subprocess.run([CADDY, "reload", "--config", CADDYFILE, "--adapter", "caddyfile", "--address", f"unix/{ADMIN_SOCK}"],
                       capture_output=True, text=True, timeout=20)
    if r.returncode:
        raise Err("caddy refused the config (the old one stays live): " + r.stderr.strip()[-300:])
    return "reloaded" + (" (https on)" if https else " (http only: run `mkcert -install` once for https)")


# ---- git context
def git(*args):
    r = subprocess.run(["git", *args], capture_output=True, text=True)
    return r.stdout.strip() if r.returncode == 0 else ""


def resolve_project(arg):
    if arg:
        return check_name("project", arg)
    top = git("rev-parse", "--show-toplevel")
    if not top:
        raise Err("no project given and not inside a git repo")
    return slug(os.path.basename(top))


def resolve_branch(arg):
    if arg is None:
        return None
    b = git("rev-parse", "--abbrev-ref", "HEAD") if arg == "auto" else arg
    return None if b in MAIN_BRANCHES else b


def url(host):
    return f"http://{host}"


# ---- commands
def cmd_ensure(a):
    project = resolve_project(a.project)
    if a.service:
        check_name("service", a.service)
    branch = resolve_branch(a.branch)
    host = hostname(project, a.service, branch)
    with locked():
        reg = load()
        e = reg["entries"].get(host)
        created = False
        if e and a.port and e["port"] != a.port and not a.force:
            raise Err(f"{host} already maps to port {e['port']} (use --force to remap)")
        if not e or (a.port and a.force):
            port = a.port or alloc_port(reg)
            clash = [h for h, x in reg["entries"].items() if x["port"] == port and h != host]
            if clash:
                raise Err(f"port {port} is already registered as {clash[0]}")
            e = reg["entries"][host] = {
                "port": port, "project": project, "service": a.service, "branch": branch,
                "rewrite": not a.keep_host, "note": a.note or "",
                "created": datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds"),
            }
            save(reg)
            created = True
            status = render(reg)
        else:
            status = "exists"
    print(f"devname: {host} -> 127.0.0.1:{e['port']} ({'created, ' + status if created else status})", file=sys.stderr)
    if a.format == "port":
        print(e["port"])
    elif a.format == "json":
        print(json.dumps({"host": host, "url": url(host), "port": e["port"], "created": created}))
    else:
        print(url(host))
    return 0


def cmd_ls(a):
    reg = load()
    rows = [(h, e["port"], "up" if port_listening(e["port"]) else "down", e.get("note", "")) for h, e in sorted(reg["entries"].items())]
    if a.json:
        print(json.dumps([{"host": h, "port": p, "upstream": s, "note": n} for h, p, s, n in rows], indent=2))
        return 0
    w = max([len(r[0]) for r in rows] + [4])
    for h, p, s, n in rows:
        print(f"{h:<{w}}  {p:<5}  {s:<4}  {n}")
    return 0


def cmd_rm(a):
    host = a.host if a.host.endswith(SUFFIX) else a.host + SUFFIX
    with locked():
        reg = load()
        if host not in reg["entries"]:
            raise Err(f"{host} is not registered")
        del reg["entries"][host]
        save(reg)
        print(f"devname: removed {host}; {render(reg)}", file=sys.stderr)
    return 0


def cmd_check(a):
    host = a.host if a.host.endswith(SUFFIX) else a.host + SUFFIX
    e = load()["entries"].get(host)
    if not e:
        print(f"{host}: not registered")
        return 1
    up = port_listening(e["port"])
    code = "-"
    try:
        req = urllib.request.Request("http://127.0.0.1/", headers={"Host": host})
        with urllib.request.urlopen(req, timeout=3) as r:
            code = r.status
    except urllib.error.HTTPError as ex:
        code = ex.code
    except OSError:
        code = "proxy down"
    print(f"{host}: port {e['port']} {'listening' if up else 'NOT listening'}, proxy answered {code}")
    return 0 if up and isinstance(code, int) and code < 500 else 1


def cmd_render(a):
    with locked():
        print("devname:", render(load()), file=sys.stderr)
    return 0


# ---- index page (devname.localhost, served by the agent next to caddy)
PAGE = """<!doctype html>
<html lang="en"><head><meta charset="utf-8">
<meta http-equiv="refresh" content="30">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>devname — local names</title>
<style>
:root {{ color-scheme: light dark; }}
body {{ font: 15px/1.5 -apple-system, "Helvetica Neue", sans-serif; margin: 2rem auto; max-width: 52rem; padding: 0 1rem; }}
h1 {{ font-size: 1.3rem; margin: 0 0 .2rem; }}
p.sum {{ color: #888; margin: 0 0 1.4rem; }}
table {{ border-collapse: collapse; width: 100%; }}
th {{ text-align: left; font-weight: 600; border-bottom: 1px solid #8884; padding: .35rem .6rem; }}
td {{ padding: .35rem .6rem; border-bottom: 1px solid #8882; }}
td.port {{ color: #888; font-variant-numeric: tabular-nums; }}
.dot {{ display: inline-block; width: .55em; height: .55em; border-radius: 50%; margin-right: .45em; }}
tr.up .dot {{ background: #2e9e44; }}
tr.down .dot {{ background: #d0483e; }}
tr.down td.name a {{ color: #888; }}
.muted {{ color: #888; }}
footer {{ margin-top: 1.4rem; color: #888; font-size: .85rem; }}
</style></head><body>
<h1>devname</h1>
<p class="sum">{n_names} names · {n_up} up · live from names.json · refreshes every 30 s</p>
<table><thead><tr><th>Name</th><th>Port</th><th>Status</th><th>Note</th></tr></thead>
<tbody>
{rows}
</tbody></table>
<footer>served by <code>devname serve</code> · <a href="/json">JSON</a></footer>
</body></html>
"""


def index_rows():
    reg = load()
    items = sorted(reg["entries"].items())
    if not items:
        return []
    with cf.ThreadPoolExecutor(max_workers=min(32, len(items))) as ex:
        ups = list(ex.map(lambda kv: port_listening(kv[1]["port"]), items))
    return [(h, e, up) for (h, e), up in zip(items, ups)]


def index_page():
    rows = index_rows()
    groups = {}
    for h, e, up in rows:
        groups.setdefault(e.get("project") or h.split(".")[0], []).append((h, e, up))
    trs = []
    for proj in sorted(groups):
        ents = sorted(groups[proj], key=lambda t: (t[1].get("service") or "", t[1].get("branch") or ""))
        for h, e, up in ents:  # main site first (no service), then branch variants, then sub-services
            name = f'<a href="//{h}/">{h}</a>'
            if e.get("branch"):
                name += f' <span class="muted">⎇ {html.escape(e["branch"])}</span>'
            cls = "up" if up else "down"
            trs.append(f'<tr class="{cls}"><td class="name">{name}</td><td class="port">{e["port"]}</td>'
                       f'<td><span class="dot"></span>{"up" if up else "down"}</td>'
                       f'<td>{html.escape(e.get("note") or "")}</td></tr>')
    return PAGE.format(n_names=len(rows), n_up=sum(1 for *_, up in rows if up), rows="\n".join(trs))


class IndexHandler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path.split("?")[0] == "/json":
            body, ctype = json.dumps(
                [{"host": h, "port": e["port"], "up": up, "project": e.get("project"),
                  "service": e.get("service"), "branch": e.get("branch"), "note": e.get("note") or ""}
                 for h, e, up in index_rows()], indent=2) + "\n", "application/json"
        else:
            body, ctype = index_page(), "text/html; charset=utf-8"
        data = body.encode()
        self.send_response(200)
        self.send_header("Content-Type", ctype)
        self.send_header("Content-Length", str(len(data)))
        self.send_header("Cache-Control", "no-store")
        self.end_headers()
        self.wfile.write(data)

    def log_message(self, *args):  # silent: the page self-refreshes every 30 s
        pass


def start_index_server():
    try:
        srv = http.server.ThreadingHTTPServer(("127.0.0.1", INDEX_PORT), IndexHandler)
    except OSError as ex:
        print(f"devname: index page unavailable ({ex})", file=sys.stderr)
        return
    threading.Thread(target=srv.serve_forever, daemon=True).start()


def cmd_serve(a):
    with locked():
        render(load(), reload=False)
    os.makedirs(STATE, exist_ok=True)
    with contextlib.suppress(FileNotFoundError):
        os.unlink(ADMIN_SOCK)
    env = dict(os.environ, XDG_DATA_HOME=STATE, XDG_CONFIG_HOME=STATE, HOME=HOME)
    caddy = subprocess.Popen([CADDY, "run", "--config", CADDYFILE, "--adapter", "caddyfile"], env=env)
    start_index_server()
    signal.signal(signal.SIGTERM, lambda *_: (caddy.terminate(), sys.exit(0)))
    return caddy.wait()


def launchd_loaded():
    return subprocess.run(["launchctl", "print", f"gui/{os.getuid()}/{LABEL}"], capture_output=True).returncode == 0


def cmd_doctor(a):
    ok = True

    def line(good, text):
        nonlocal ok
        ok = ok and good
        print(("PASS  " if good else "FAIL  ") + text)
    line(os.path.exists(CADDY), f"caddy at {CADDY}")
    line(launchd_loaded(), f"launchd agent {LABEL} loaded")
    line(os.path.exists(ADMIN_SOCK), "caddy admin socket present")
    try:
        urllib.request.urlopen(urllib.request.Request("http://127.0.0.1/", headers={"Host": "doctor.invalid"}), timeout=3)
        answered = True
    except urllib.error.HTTPError:
        answered = True
    except OSError:
        answered = False
    line(answered, "proxy answers on 127.0.0.1:80")
    code = None
    try:
        with urllib.request.urlopen(urllib.request.Request("http://127.0.0.1/", headers={"Host": INDEX_HOST}), timeout=3) as r:
            code = r.status
    except urllib.error.HTTPError as ex:
        code = ex.code
    except OSError:
        pass
    line(code == 200, f"index page on {INDEX_HOST} (got {code})")
    root = subprocess.run([MKCERT, "-CAROOT"], capture_output=True, text=True).stdout.strip()
    line(os.path.exists(os.path.join(root, "rootCA.pem")), "mkcert root CA exists (https; trust it with `mkcert -install`)")
    line(have_https(), "https cert issued for the registered names")
    print(f"{len(load()['entries'])} names registered")
    return 0 if ok else 1


def cmd_agent(a):
    if a.action == "status":
        print("loaded" if launchd_loaded() else "not loaded")
        return 0
    plist = f"""<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
<key>Label</key><string>{LABEL}</string>
<key>ProgramArguments</key><array><string>{os.path.abspath(__file__)}</string><string>serve</string></array>
<key>RunAtLoad</key><true/>
<key>KeepAlive</key><true/>
<key>StandardOutPath</key><string>{LOGDIR}/caddy.log</string>
<key>StandardErrorPath</key><string>{LOGDIR}/caddy.log</string>
</dict></plist>
"""
    os.makedirs(LOGDIR, exist_ok=True)
    with open(PLIST, "w") as fh:
        fh.write(plist)
    domain = f"gui/{os.getuid()}"
    subprocess.run(["launchctl", "bootout", f"{domain}/{LABEL}"], capture_output=True)
    r = subprocess.run(["launchctl", "bootstrap", domain, PLIST], capture_output=True, text=True)
    if r.returncode:  # error 5 is the known transient: retry once
        r = subprocess.run(["launchctl", "bootstrap", domain, PLIST], capture_output=True, text=True)
    if r.returncode:
        raise Err("launchctl bootstrap failed: " + r.stderr.strip())
    print(f"devname: agent {LABEL} installed and loaded", file=sys.stderr)
    return 0


def main(argv=None):
    p = argparse.ArgumentParser(prog="devname", description=__doc__.split("\n")[0])
    sub = p.add_subparsers(dest="cmd", required=True)
    e = sub.add_parser("ensure", help="idempotent: URL if it exists, else allocate + register + reload")
    e.add_argument("project", nargs="?")
    e.add_argument("--service")
    e.add_argument("--branch", help="a branch name, or 'auto' = the cwd's git branch (main/master get no suffix)")
    e.add_argument("--port", type=int, help="adopt an existing server's port instead of allocating")
    e.add_argument("--force", action="store_true", help="with --port: remap an existing name")
    e.add_argument("--keep-host", action="store_true", help="do not rewrite Host to 127.0.0.1:<port> (default: rewrite)")
    e.add_argument("--note")
    e.add_argument("--format", choices=["url", "port", "json"], default="url")
    e.set_defaults(fn=cmd_ensure)
    s = sub.add_parser("ls"); s.add_argument("--json", action="store_true"); s.set_defaults(fn=cmd_ls)
    s = sub.add_parser("rm"); s.add_argument("host"); s.set_defaults(fn=cmd_rm)
    s = sub.add_parser("check"); s.add_argument("host"); s.set_defaults(fn=cmd_check)
    sub.add_parser("render").set_defaults(fn=cmd_render)
    sub.add_parser("serve").set_defaults(fn=cmd_serve)
    sub.add_parser("doctor").set_defaults(fn=cmd_doctor)
    s = sub.add_parser("agent"); s.add_argument("action", choices=["install", "status"]); s.set_defaults(fn=cmd_agent)
    a = p.parse_args(argv)
    try:
        return a.fn(a)
    except Err as ex:
        print(f"devname: {ex}", file=sys.stderr)
        return 2


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