#!/bin/sh
# scripts/zig-fetch-deps — populate zig's global cache with the carved
# (private, Codeberg-hosted) mgf-hrb-* package dependencies.
#
# WHY this exists: the broker's Zig deps (E2 carve — mgf-hrb-model, …)
# live in PRIVATE repos under the limited-visibility `magogi-admin`
# account, so they can't be fetched anonymously. And zig's built-in git
# client only accepts credentials embedded in the URL — it ignores
# ~/.netrc and git credential helpers. Embedding a token in the
# committed build.zig.zon would leak it, so instead this script injects a
# token at fetch time into each `git+https://codeberg.org/...` dep URL
# found in hrb-code/build.zig.zon, fetching each into the
# content-addressed global cache. Afterwards `zig build` resolves every
# dependency BY HASH with no network and no credentials.
#
# Run it once after cloning, and again whenever a dep's pinned
# commit/hash changes. Idempotent: an already-cached package re-fetches
# cheaply.
#
# Token source (first found wins):
#   1. $CODEBERG_TOKEN          (CI: set this as a secret)
#   2. my_stuff/ssh_key/codeberg_token.txt  (local dev; gitignored)
#
# The token is NEVER written to disk or to any committed file.
set -eu

REPO_ROOT="$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)"
ZIG="${ZIG:-$REPO_ROOT/.venv/lib/python3.13/site-packages/ziglang/zig}"
ZON="$REPO_ROOT/hrb-code/build.zig.zon"

TOKEN="${CODEBERG_TOKEN:-}"
if [ -z "$TOKEN" ] && [ -f "$REPO_ROOT/my_stuff/ssh_key/codeberg_token.txt" ]; then
    TOKEN="$(tr -d '\n' < "$REPO_ROOT/my_stuff/ssh_key/codeberg_token.txt")"
fi
if [ -z "$TOKEN" ]; then
    printf 'zig-fetch-deps: no token found. Set CODEBERG_TOKEN or provide\n' >&2
    printf '  my_stuff/ssh_key/codeberg_token.txt\n' >&2
    exit 1
fi

urls="$(grep -oE 'git\+https://codeberg\.org/[^"]+' "$ZON" || true)"
if [ -z "$urls" ]; then
    printf 'zig-fetch-deps: no git+https codeberg deps in %s (nothing to do)\n' "$ZON"
    exit 0
fi

printf '%s\n' "$urls" | while IFS= read -r url; do
    [ -n "$url" ] || continue
    authed="$(printf '%s' "$url" | sed "s#git+https://codeberg.org/#git+https://magogi-admin:${TOKEN}@codeberg.org/#")"
    printf 'fetch: %s\n' "$url"
    # zig fetch must run from a package dir (one with build.zig).
    ( cd "$REPO_ROOT/hrb-code" && "$ZIG" fetch "$authed" >/dev/null )
done

printf 'zig-fetch-deps: all carved deps are in the global cache.\n'
