#!/usr/bin/env python3 """Regenerate the self-updating blocks of jblu/.profile. Runs in Gitea Actions (.gitea/workflows/readme.yml) and locally. Stdlib only. Blocks are delimited by HTML comment markers in README.md: ... coloured terminal card ... "N/M services up" line ... featured repos + release ... newest commits ... newest pull requests ... newest done Vikunja tasks A missing marker is a no-op, so a section can be deleted from the README without breaking the job. A failing data source keeps the previous block text and makes the run exit 1, so a dead API never blanks a section. Usage: gen_readme.py dry run: print the regenerated README gen_readme.py --write write README.md in place gen_readme.py --check exit 1 if README.md is stale gen_readme.py --check-links exit 1 if any link is not publicly reachable gen_readme.py --svg DIR also write terminal-{dark,light}.svg into DIR gen_readme.py --terminal-image render the terminal block as + SVG instead of inline
 (needs --svg)

Gitea keeps style="color:..." on spans, so it gets the inline 
. GitHub's
sanitizer strips style, class and inline , so the GitHub workflow runs
with --svg + --terminal-image and commits the two SVGs next to README.md.

Environment:
  GITEA_TOKEN             optional. Set (even empty) wins; unset falls back to
                          ~/.config/gitea/qbit-maid-push.token. Empty means
                          anonymous, which is enough for the public repos.
  KOMODO_API_KEY/SECRET   optional; without them the stack/host counts are kept
  VIKUNJA_TOKEN           optional; without it the completed block is kept

Every data source is reached over its public FQDN (git.jonb.io, k.jonb.io,
 todo.jonb.io, up.jonb.io), so the same script runs on the Gitea runner and on
GitHub Actions.
"""

import argparse
import json
import os
import re
import sys
import urllib.error
import urllib.request
from datetime import datetime, timezone
from pathlib import Path

HERE = Path(__file__).resolve().parent
ROOT = HERE.parent
README = ROOT / "README.md"
CONFIG = HERE / "readme.json"
LOCAL_TOKEN = Path.home() / ".config/gitea/qbit-maid-push.token"

# Public URLs that legitimately refuse non-browser clients.
LINK_ALLOWLIST = {
    "https://www.linkedin.com/in/jonathanbranan/",
}


# ---------------------------------------------------------------- http


def http_json(url, headers=None, data=None, timeout=25):
    body = json.dumps(data).encode() if data is not None else None
    req = urllib.request.Request(url, data=body, headers=headers or {})
    if body is not None:
        req.add_header("Content-Type", "application/json")
    with urllib.request.urlopen(req, timeout=timeout) as r:
        return json.load(r)


def gitea_token():
    """Explicit GITEA_TOKEN wins (empty = anonymous); unset falls back to the
    local token file, then to anonymous."""
    tok = os.environ.get("GITEA_TOKEN")
    if tok is not None:
        return tok.strip()
    if LOCAL_TOKEN.exists():
        return LOCAL_TOKEN.read_text().strip()
    return ""


def gitea(path, tok):
    headers = {"Authorization": "token " + tok} if tok else {}
    return http_json("https://git.jonb.io/api/v1" + path, headers=headers)


# ---------------------------------------------------------------- helpers


def one_line(text, limit):
    line = re.sub(r"\s+", " ", (text or "").strip().splitlines()[0] if (text or "").strip() else "")
    return line if len(line) <= limit else line[: limit - 1].rstrip() + "…"


def ago(iso):
    if not iso:
        return ""
    try:
        dt = datetime.fromisoformat(iso.replace("Z", "+00:00"))
    except ValueError:
        return ""
    secs = int((datetime.now(timezone.utc) - dt).total_seconds())
    if secs < 3600:
        return f"{max(secs // 60, 1)}m ago"
    if secs < 86400:
        return f"{secs // 3600}h ago"
    if secs < 86400 * 30:
        return f"{secs // 86400}d ago"
    if secs < 86400 * 365:
        return f"{secs // (86400 * 30)}mo ago"
    return f"{secs // (86400 * 365)}y ago"


def replace_block(text, name, body):
    """Replace a marked block. A missing marker is a no-op, not an error."""
    pat = re.compile(rf"()(.*?)()", re.S)
    if not pat.search(text):
        return text
    return pat.sub(lambda m: f"{m.group(1)}\n{body}\n{m.group(3)}", text)


def previous_int(text, pattern, default=0):
    # the rendered blocks wrap numbers in , so match
    # against the tag-stripped text or the fallback silently yields 0
    plain = re.sub(r"<[^>]+>", "", text)
    m = re.search(pattern, plain)
    if m:
        return int(m.group(1))
    # image mode: the counts live in the committed SVG, not in the README
    for svg in sorted(README.parent.glob("terminal-*.svg")):
        m = re.search(pattern, svg.read_text())
        if m:
            return int(m.group(1))
    return default


# ---------------------------------------------------------------- sources


def kuma_counts(cfg):
    base = cfg["kuma"]["base"]
    page = cfg["kuma"]["page"]
    hb = http_json(f"{base}/status-page/heartbeat/{page}").get("heartbeatList", {})
    up = sum(1 for v in hb.values() if v and v[-1].get("status") == 1)
    return up, len(hb)


def komodo_counts(cfg):
    """(stacks, hosts) from Komodo, or (None, None) when no key is configured."""
    key = os.environ.get("KOMODO_API_KEY", "").strip()
    secret = os.environ.get("KOMODO_API_SECRET", "").strip()
    if not key or not secret:
        return None, None
    base = cfg["komodo"]["base"]
    headers = {"X-Api-Key": key, "X-Api-Secret": secret}
    stacks = http_json(f"{base}/read/GetStacksSummary", headers=headers, data={})
    servers = http_json(f"{base}/read/GetServersSummary", headers=headers, data={})
    return stacks["total"], servers["total"] + cfg["komodo"].get("extra_hosts", 0)


def vikunja_done(cfg):
    tok = os.environ.get("VIKUNJA_TOKEN", "").strip()
    if not tok:
        return None
    base = cfg["vikunja"]["base"]
    project = cfg["vikunja"]["project"]
    tasks = http_json(
        f"{base}/api/v1/projects/{project}/tasks?per_page=100",
        headers={"Authorization": "Bearer " + tok},
    )
    done = [t for t in tasks if t.get("done") and t.get("done_at")]
    done.sort(key=lambda t: t["done_at"], reverse=True)
    return done


# ---------------------------------------------------------------- blocks


# ---------------------------------------------------------------- terminal card
#
# The card is built once as lines of (text, colour-key-or-None) segments and
# then rendered two ways: inline 
 with coloured spans for Gitea (whose
# sanitizer allows style="color:..."), and a committed SVG for GitHub (whose
# sanitizer strips style, class and inline  entirely).

SVG_FONT = (
    'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, '
    '"DejaVu Sans Mono", monospace'
)
SVG_THEMES = {
    "dark": ("#0d1117", "#c9d1d9"),
    "light": ("#f6f8fa", "#1f2328"),
}


def terminal_lines(cfg, stacks, hosts):
    """The card as lines of (text, colour-key-or-None) segments."""
    tr = cfg["traceroute"]
    man = cfg["man"]
    prompt = [("jonathan@core", "prompt"), (":", None), ("~", "path"), ("$", "muted")]
    lines = [
        prompt + [(" whoami", None)],
        [
            ("Jonathan Branan — ", None),
            (cfg["role"], "value"),
            (" at " + cfg["employer"], None),
        ],
        [],
        prompt + [(" uptime", None)],
        [
            ("up ", None),
            (str(hosts), "value"),
            (" hosts · ", None),
            (str(stacks), "value"),
            (" stacks · ", None),
            ("1", "value"),
            (" very patient wife", None),
        ],
        [],
        prompt + [(" traceroute " + tr["target"], None)],
        [
            (
                f"traceroute to {tr['target']} ({tr['target_ip']}), "
                "30 hops max, 60 byte packets",
                "muted",
            )
        ],
    ]
    for i, hop in enumerate(tr["hops"], 1):
        a, b, d = hop["ms"]
        lines.append(
            [
                (f"{i:2d}", "muted"),
                ("  ", None),
                (f"{hop['name']:<18}", "path"),
                (f"{a:>7.3f} ms {b:>7.3f} ms {d:>7.3f} ms", "muted"),
            ]
        )
    lines += [[], prompt + [(" man jonathan", None)], [(man["header"], "muted")]]
    for title, body in man["sections"]:
        lines += [[], [(title, "path")]]
        lines += [[(line, None)] for line in body]
    lines += [[], [(man["footer"], "muted")]]
    return lines


def _esc(text):
    return text.replace("&", "&").replace("<", "<").replace(">", ">")


def render_terminal_html(lines, palette):
    """Inline coloured 
 - Gitea keeps style="color:..." on spans."""
    out = []
    for segs in lines:
        out.append(
            "".join(
                f'{_esc(text)}'
                if key
                else _esc(text)
                for text, key in segs
            )
        )
    return "
" + "\n".join(out) + "
" def terminal_geometry(lines, font_size=14, pad=20): """Pixel size of the card. 0.62em per column is the widest common monospace advance, so the box never clips whatever font the viewer has.""" cols = max((sum(len(text) for text, _ in segs) for segs in lines), default=1) width = int(round(pad * 2 + cols * font_size * 0.62)) height = int(round(pad * 2 + len(lines) * font_size * 1.5)) return width, height def render_terminal_svg(lines, palette, theme="dark", font_size=14, pad=20): """The same card as a standalone SVG - GitHub strips inline .""" bg, fg = SVG_THEMES[theme] width, height = terminal_geometry(lines, font_size, pad) line_h = font_size * 1.5 out = [ f'', f'', f'', ] for i, segs in enumerate(lines): if not segs: continue y = round(pad + font_size * 0.85 + i * line_h, 2) spans = "".join( f'{_esc(text)}' for text, key in segs ) # xml:space must sit on the itself - on an ancestor Chrome # collapses the leading and repeated spaces the card is aligned with out.append(f'{spans}') out += ["", ""] return "\n".join(out) + "\n" def terminal_image_block(width): """ so the card follows the viewer's light/dark theme.""" return ( "\n" ' \n' f' \n' "" ) def status_block(cfg, up, total): p = cfg["palette"] ok = up == total dot = "●" if ok else "◐" colour = p["prompt"] if ok else p["value"] return ( f'{dot} {up}/{total} services up · ' f'refreshed daily' ) def working_on_block(cfg, tok): lines = [] for name in cfg["featured_repos"]: repo = gitea(f"/repos/jblu/{name}", tok) desc = one_line(repo.get("description") or "", 88) if not desc: # no description set — say something true instead of a bare dash desc = f'{repo.get("language") or "code"} · updated {ago(repo.get("updated_at"))}' tag = "" try: rel = gitea(f"/repos/jblu/{name}/releases?limit=1", tok) if rel: tag = f' · `{rel[0]["tag_name"]}`' except Exception: pass lines.append(f'- [**{name}**]({repo["html_url"]}) — {desc}{tag}') return "\n".join(lines) def activity_block(cfg, tok): rows = [] for name in cfg["featured_repos"]: for c in gitea(f"/repos/jblu/{name}/commits?limit=5&stat=false", tok): msg = c["commit"]["message"].strip() if msg.startswith(("Merge pull request", "Merge PR")): continue # the PR block already lists it rows.append((c["commit"]["author"]["date"], name, c)) rows.sort(key=lambda r: r[0], reverse=True) lines = [ f'- [{one_line(c["commit"]["message"], 64)}]({c["html_url"]}) — {name} · {ago(date)}' for date, name, c in rows[: cfg["limits"]["activity"]] ] return "\n".join(lines) def prs_block(cfg, tok): rows = [] for name in cfg["featured_repos"]: for p in gitea(f"/repos/jblu/{name}/pulls?state=all&limit=5&sort=recentupdate", tok): rows.append((p["updated_at"], name, p)) rows.sort(key=lambda r: r[0], reverse=True) lines = [ f'- [{one_line(p["title"], 64)}]({p["html_url"]}) — {name} · {ago(date)}' for date, name, p in rows[: cfg["limits"]["prs"]] ] return "\n".join(lines) def completed_block(cfg, done): lines = [ f'- {one_line(t["title"], 80)} · {ago(t["done_at"])}' for t in done[: cfg["limits"]["completed"]] ] return "\n".join(lines) # ---------------------------------------------------------------- build def build(svg_dir=None, terminal_image=False): cfg = json.loads(CONFIG.read_text()) text = README.read_text() tok = gitea_token() errors = [] def apply(name, fn): nonlocal text try: body = fn() except Exception as exc: # keep the previous block, report, fail the run errors.append(f"{name}: {type(exc).__name__}: {exc}") return if body: text = replace_block(text, name, body) stacks, hosts = None, None try: stacks, hosts = komodo_counts(cfg) except Exception as exc: errors.append(f"komodo: {type(exc).__name__}: {exc}") if stacks is None: stacks = previous_int(text, r"(\d+) stacks") if hosts is None: hosts = previous_int(text, r"up (\d+) hosts") try: lines = terminal_lines(cfg, stacks, hosts) except Exception as exc: errors.append(f"terminal: {type(exc).__name__}: {exc}") else: if svg_dir: svg_dir.mkdir(parents=True, exist_ok=True) for theme in SVG_THEMES: (svg_dir / f"terminal-{theme}.svg").write_text( render_terminal_svg(lines, cfg["palette"], theme) ) if terminal_image: width, _ = terminal_geometry(lines) text = replace_block(text, "terminal", terminal_image_block(width)) else: text = replace_block( text, "terminal", render_terminal_html(lines, cfg["palette"]) ) try: up, total = kuma_counts(cfg) except Exception as exc: errors.append(f"kuma: {type(exc).__name__}: {exc}") else: apply("status", lambda: status_block(cfg, up, total)) apply("working-on", lambda: working_on_block(cfg, tok)) apply("activity", lambda: activity_block(cfg, tok)) apply("prs", lambda: prs_block(cfg, tok)) try: done = vikunja_done(cfg) except Exception as exc: errors.append(f"vikunja: {type(exc).__name__}: {exc}") else: if done is not None: apply("completed", lambda: completed_block(cfg, done)) for err in errors: print(f"warn: {err}", file=sys.stderr) return text, errors # ---------------------------------------------------------------- link check def check_links(): text = README.read_text() urls = sorted(set(re.findall(r"https?://[^\s\)\"'<>]+", text))) bad = [] for url in urls: if url in LINK_ALLOWLIST: print(f"skip {url} (bot-blocked by design)") continue try: req = urllib.request.Request( url, headers={"User-Agent": "Mozilla/5.0 (profile-readme link check)"} ) with urllib.request.urlopen(req, timeout=20) as r: code = r.status except urllib.error.HTTPError as exc: code = exc.code except Exception as exc: code = type(exc).__name__ ok = code == 200 print(f"{'ok ' if ok else 'FAIL '} {code} {url}") if not ok: bad.append((url, code)) if bad: print(f"\n{len(bad)} unreachable link(s) — dead for anyone not logged in.") return 1 print(f"\nall {len(urls)} links public") return 0 # ---------------------------------------------------------------- main def main(): ap = argparse.ArgumentParser() ap.add_argument("--write", action="store_true") ap.add_argument("--check", action="store_true") ap.add_argument("--check-links", action="store_true") ap.add_argument( "--svg", metavar="DIR", help="also write terminal-{dark,light}.svg into DIR (GitHub needs an image)", ) ap.add_argument( "--terminal-image", action="store_true", help="render the terminal block as + SVG instead of inline
",
    )
    args = ap.parse_args()

    if args.check_links:
        return check_links()
    if args.terminal_image and not args.svg:
        ap.error("--terminal-image needs --svg DIR (the  points at those files)")

    new, errors = build(
        svg_dir=Path(args.svg) if args.svg else None,
        terminal_image=args.terminal_image,
    )
    old = README.read_text()

    if args.check:
        if new != old:
            print("README.md is stale")
            return 1
        print("README.md is current")
        return 1 if errors else 0
    if args.write:
        if new != old:
            README.write_text(new)
            print(f"wrote {README}")
        else:
            print("no change")
        return 1 if errors else 0

    sys.stdout.write(new)
    return 1 if errors else 0


if __name__ == "__main__":
    raise SystemExit(main())