#!/usr/bin/env bash
# fj-git <agent> <git args...>
#
# Runs git with a pipeline agent's Forgejo identity. Never stores tokens:
# credentials are read per-invocation from ~/.pi/agent/fj-agent-credentials.json
# and passed via a one-shot authenticated URL on push.
#
# Examples:
#   fj-git sculptor add -A
#   fj-git sculptor commit -m "sculpt: base mesh"
#   fj-git sculptor push origin workflow/texturer
set -euo pipefail

AGENT="${1:-}"; [ -n "$AGENT" ] || { echo "usage: fj-git <agent> <git args...>" >&2; exit 2; }
shift
CREDS="${FJ_AGENT_CREDENTIALS:-$HOME/.pi/agent/fj-agent-credentials.json}"
[ -f "$CREDS" ] || { echo "fj-git: $CREDS not found" >&2; exit 1; }

eval "$(python3 - "$AGENT" "$CREDS" <<'PY'
import json, sys, shlex, os
agent, path = sys.argv[1], sys.argv[2]
d = json.load(open(os.path.expanduser(path)))
e = d.get(agent) or d.get("mm-agent-" + agent)
if not e:
    print(f"echo 'fj-git: unknown agent {agent}' >&2; exit 2")
else:
    print(f"FJ_USER={shlex.quote(agent)}")
    print(f"FJ_TOKEN={shlex.quote(e['token'])}")
    print(f"FJ_EMAIL={shlex.quote(e.get('email', agent + '@agents.miri.work'))}")
PY
)"

export GIT_AUTHOR_NAME="$AGENT" GIT_COMMITTER_NAME="$AGENT"
export GIT_AUTHOR_EMAIL="$FJ_EMAIL" GIT_COMMITTER_EMAIL="$FJ_EMAIL"

if [ "${1:-}" = "push" ]; then
  shift
  remote="${1:-origin}"
  [ "$#" -gt 0 ] && shift   # drop remote name; remaining args are refspecs/options
  url="$(git remote get-url "$remote")"
  auth="$(FJ_URL="$url" FJ_USER="$FJ_USER" FJ_TOKEN="$FJ_TOKEN" python3 - <<'PY'
import os, re
url = os.environ["FJ_URL"]
user, token = os.environ["FJ_USER"], os.environ["FJ_TOKEN"]
print(re.sub(r"^(https?://)", rf"\1{user}:{token}@", url))
PY
)"
  exec git push "$auth" "$@"
fi

exec git "$@"
