main
Colby Knox 0.2.99: dashboard picks a Windows machine only on a click, Works here section with a Linux Altium 365 bridge (#33) 687f09e
"""The dashboard's "Works here" section (altium-bridge#33): what runs in this workspace, with no Altium Designer and
no Windows machine.

- Altium 365 (the altium_a365_* lane: workspace sign-in, status, the cloud library). The bridge's cloud lane has no
  Altium Designer dependency, so a Linux build of the same bridge serves it here. The build is a release asset; the
  package carries only linux-bridge.json (version, file, sha256), and the binary is fetched and checked on first use.
- Library conversion with Adom LBR (Altium .SchLib/.PcbLib/.IntLib to and from KiCad and EAGLE), through the
  `adom-lbr` CLI when it is installed.
"""
import atexit
import hashlib
import json
import os
import shutil
import socket
import stat
import subprocess
import time
import urllib.request
from pathlib import Path

HERE = Path(__file__).resolve().parent
A365_VERBS = {
    "a365_status": "a365_status",
    "a365_configure": "a365_configure",
    "a365_sign_in": "a365_oauth_begin",
    "a365_sign_in_status": "a365_oauth_status",
    "a365_sign_in_cancel": "a365_oauth_cancel",
    "a365_library": "a365_library_overview",
    "a365_sign_out": "a365_logout",
}
_proc = {"p": None, "port": None}


def _cache_dir() -> Path:
    base = os.environ.get("XDG_CACHE_HOME") or os.path.join(os.path.expanduser("~"), ".cache")
    return Path(base) / "adom-altium-bridge"


def release_info():
    """linux-bridge.json beside this file: {version, file, sha256, size}. None in a dev tree without one."""
    try:
        return json.loads((HERE / "linux-bridge.json").read_text(encoding="utf-8"))
    except Exception:
        return None


def _sha256(path: Path) -> str:
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for chunk in iter(lambda: f.read(1 << 20), b""):
            h.update(chunk)
    return h.hexdigest()


def binary():
    """The Linux bridge, fetched once per version and checked against the release's sha256. (path, error)."""
    dev = os.environ.get("ADOM_ALTIUM_LINUX_BRIDGE")
    if dev:
        return (Path(dev), None) if Path(dev).is_file() else (None, f"ADOM_ALTIUM_LINUX_BRIDGE={dev} does not exist")
    info = release_info()
    if not info:
        return None, "this install has no Linux bridge record (linux-bridge.json)"
    dest = _cache_dir() / "bin" / f"altium-bridge-{info['version']}"
    if dest.is_file() and _sha256(dest) == info["sha256"]:
        return dest, None
    url = f"https://wiki.adom.inc/download/adom/altium-bridge/{info['version']}/{info['file']}"
    req = urllib.request.Request(url, headers={"User-Agent": "altium-dashboard"})
    key = Path("/var/run/adom/api-key")
    if key.is_file():  # an insiders build is served to signed-in workspaces only
        req.add_header("Authorization", "Bearer " + key.read_text().strip())
    try:
        dest.parent.mkdir(parents=True, exist_ok=True)
        tmp = dest.with_suffix(".part")
        with urllib.request.urlopen(req, timeout=120) as r, open(tmp, "wb") as f:
            shutil.copyfileobj(r, f)
        if _sha256(tmp) != info["sha256"]:
            tmp.unlink(missing_ok=True)
            return None, "the downloaded Linux bridge did not match its release checksum; nothing was run"
        tmp.chmod(tmp.stat().st_mode | stat.S_IXUSR)
        tmp.replace(dest)
        return dest, None
    except Exception as e:
        return None, f"could not fetch the Linux bridge: {str(e)[:160]}"


def _free_port() -> int:
    s = socket.socket()
    s.bind(("127.0.0.1", 0))
    port = s.getsockname()[1]
    s.close()
    return port


def _post(port, verb, args, timeout):
    body = json.dumps({"command": verb, "args": args or {}}).encode()
    req = urllib.request.Request(f"http://127.0.0.1:{port}/command", data=body,
                                 headers={"Content-Type": "application/json"})
    with urllib.request.urlopen(req, timeout=timeout) as r:
        return json.loads(r.read())


def _ping(port) -> bool:
    try:
        with urllib.request.urlopen(f"http://127.0.0.1:{port}/ping", timeout=1):
            return True
    except Exception:
        return False


def _record() -> Path:
    return _cache_dir() / "linux-bridge.run.json"


def _ensure_bridge():
    p = _proc["p"]
    if p is not None and p.poll() is None:
        return _proc["port"], None
    path, err = binary()
    if err:
        return None, err
    # a bridge from an earlier dashboard process (restarted, or killed without its exit hook) is reused, not
    # doubled; one from another version is stopped
    try:
        rec = json.loads(_record().read_text())
        if rec.get("port") and _ping(rec["port"]):
            if rec.get("path") == str(path):
                _proc["port"] = rec["port"]
                return rec["port"], None
            if rec.get("pid"):
                os.kill(int(rec["pid"]), 15)
    except Exception:
        pass
    port = _free_port()
    _cache_dir().mkdir(parents=True, exist_ok=True)
    log = open(_cache_dir() / "linux-bridge.log", "ab")
    try:
        _proc["p"] = subprocess.Popen([str(path), "--port", str(port)], stdout=log, stderr=log,
                                      stdin=subprocess.DEVNULL, start_new_session=True)
    except OSError as e:
        return None, f"the Linux bridge would not start on this machine: {e}"
    _proc["port"] = port
    for _ in range(50):
        if _ping(port):
            _record().write_text(json.dumps({"pid": _proc["p"].pid, "port": port, "path": str(path)}))
            return port, None
        if _proc["p"].poll() is not None:
            return None, "the Linux bridge exited at start (see ~/.cache/adom-altium-bridge/linux-bridge.log)"
        time.sleep(0.1)
    return None, "the Linux bridge did not answer within 5 s"


@atexit.register
def _stop():
    p = _proc["p"]
    if p is not None and p.poll() is None:
        p.terminate()


def a365(action, args=None, timeout=90):
    verb = A365_VERBS.get(action)
    if not verb:
        return {"success": False, "errorCode": "unknown_action", "error": f"unknown Altium 365 action '{action}'"}
    port, err = _ensure_bridge()
    if err:
        return {"success": False, "errorCode": "linux_bridge_unavailable", "error": err}
    try:
        return _post(port, verb, args, timeout)
    except Exception as e:
        return {"success": False, "errorCode": "linux_bridge_error", "error": str(e)[:200]}


def lbr_open():
    """Start (or find) the Adom LBR dashboard and hand back its URL."""
    exe = shutil.which("adom-lbr")
    if not exe:
        return {"success": False, "errorCode": "adom_lbr_missing", "error": "Adom LBR is not installed in this workspace",
                "install": "adom-wiki pkg install adom/adom-lbr"}
    try:
        p = subprocess.run([exe, "dashboard", "serve", "--print-url"], capture_output=True, text=True, timeout=60)
    except Exception as e:
        return {"success": False, "errorCode": "adom_lbr_error", "error": str(e)[:200]}
    url = next((w for w in (p.stdout or "").split() if w.startswith("http")), None)
    return {"success": bool(url), "url": url, "error": None if url else (p.stderr or p.stdout or "")[:200]}


def status():
    """The section's state: cheap, and never starts anything but the local Linux bridge."""
    a = a365("a365_status", timeout=20)
    return {
        "a365": {"available": a.get("errorCode") not in ("linux_bridge_unavailable", "linux_bridge_error"),
                 "configured": bool(a.get("configured")), "signedIn": bool(a.get("hasToken")),
                 "workspace": a.get("workspace"), "error": a.get("error") or None},
        "lbr": {"installed": bool(shutil.which("adom-lbr")), "install": "adom-wiki pkg install adom/adom-lbr"},
        "_hint": "These run in this workspace, with no Altium Designer and no Windows machine: "
                 "POST /api/here {action: a365_status|a365_configure|a365_sign_in|a365_sign_in_status|"
                 "a365_library|a365_sign_out|lbr_open, args}.",
    }


def action(name, args=None):
    if name == "lbr_open":
        return lbr_open()
    return a365(name, args)