#!/bin/sh
# gh shim — broker auth for agent-typed gh (github-node-provisioning-scope.md N4).
#
# Sits ahead of the real gh on the box PATH (~/.local/bin symlink, ensureViewCli).
# For the PR-surface command families (pr / run / api / issue / search) it asks
# the local agent loopback for a per-repo broker token derived from the cwd's
# origin remote and execs the REAL gh with GH_TOKEN set for THIS invocation only
# — in-memory, per-exec, nothing on disk (P1-D1). Everything else, an already-set
# token env, an uncovered repo, or an unreachable agent runs gh unchanged (the
# keyring fallback, until phase R). Actions under the broker are actored by the
# App bot (P1-D8) — prs.js adds the on-behalf-of breadcrumbs.

self="$(readlink -f "$0" 2>/dev/null || echo "$0")"
real=""
OLDIFS="$IFS"
IFS=:
for d in $PATH; do
  c="${d:-.}/gh"
  [ -x "$c" ] || continue
  [ "$(readlink -f "$c" 2>/dev/null || echo "$c")" = "$self" ] && continue
  real="$c"
  break
done
IFS="$OLDIFS"
if [ -z "$real" ]; then
  echo "gh: real gh binary not found behind the bostrat shim" >&2
  exit 127
fi

case "$1" in
  pr|run|api|issue|search) ;;
  *) exec "$real" "$@" ;;
esac
if [ -n "$GH_TOKEN" ] || [ -n "$GITHUB_TOKEN" ]; then
  exec "$real" "$@"
fi

origin="$(git config --get remote.origin.url 2>/dev/null)"
slug="$(printf '%s' "$origin" | sed -nE 's#.*github\.com[:/]+##p' | sed -E 's#\.git$##; s#/+$##')"
case "$slug" in
  */*) ;;
  *) exec "$real" "$@" ;;
esac

agent_url="${BOSTRAT_AGENT_URL:-http://127.0.0.1:3362}"
# /api/github/token is a SENSITIVE route (api-token.js rule 2): it requires the
# node API token even from loopback. Same uid, same file the agent minted it to.
ntoken="${BOSTRAT_NODE_API_TOKEN:-}"
if [ -z "$ntoken" ]; then
  ntoken="$(cat "${BOSTRAT_STATE_DIR:-$HOME/.bostrat}/api-token" 2>/dev/null | tr -d '[:space:]')"
fi
if [ -n "$ntoken" ]; then
  token="$(curl -fsS --max-time 10 -H "x-bostrat-token: $ntoken" "$agent_url/api/github/token?repo=$slug" 2>/dev/null \
    | sed -nE 's/.*"token":"([^"]+)".*/\1/p')"
else
  token="$(curl -fsS --max-time 10 "$agent_url/api/github/token?repo=$slug" 2>/dev/null \
    | sed -nE 's/.*"token":"([^"]+)".*/\1/p')"
fi
if [ -n "$token" ]; then
  GH_TOKEN="$token" exec "$real" "$@"
fi
exec "$real" "$@"
