#!/bin/sh
# git credential helper for BOSS (credential.helper=boss). Answers `get` only;
# `store` / `erase` are ignored, so a failed clone can never wipe anyone's
# ~/.git-credentials.
#
# - In a BOSS agent run (BOSS_BB_PROXY and BOSS_BB_TOKEN set) git reaches
#   bitbucket.org through BOSS's git proxy (url.<proxy>/git/.insteadOf), and
#   this helper answers the proxy's challenge with the run's own token. The
#   agent holds no Bitbucket credential; the proxy pushes as BOSS and enforces
#   the branch rules (docs/agent-autonomy.md).
# - Otherwise (BOSS's own processes, a developer's machine) it answers for
#   https://bitbucket.org only, from BITBUCKET_USER / BITBUCKET_API_TOKEN.
# Any other host gets no answer.
protocol=""
host=""
while IFS= read -r line; do
  [ -z "$line" ] && break
  case "$line" in
    protocol=*) protocol="${line#protocol=}" ;;
    host=*) host="${line#host=}" ;;
  esac
done
cat >/dev/null 2>&1 || true
[ "$1" = get ] || exit 0

if [ -n "${BOSS_BB_PROXY:-}" ] && [ -n "${BOSS_BB_TOKEN:-}" ]; then
  proxy_rest="${BOSS_BB_PROXY#*://}"
  proxy_scheme="${BOSS_BB_PROXY%%://*}"
  proxy_host="${proxy_rest%%/*}"
  if [ "$protocol" = "$proxy_scheme" ] && [ "$host" = "$proxy_host" ]; then
    printf 'username=boss-run\npassword=%s\n' "$BOSS_BB_TOKEN"
  fi
  exit 0
fi

[ "$protocol" = https ] && [ "$host" = bitbucket.org ] || exit 0
[ -n "${BITBUCKET_API_TOKEN:-}" ] || exit 0
printf 'username=%s\npassword=%s\n' "${BITBUCKET_USER:-x-bitbucket-api-token-auth}" "$BITBUCKET_API_TOKEN"
