#!/usr/bin/env bash
set -euo pipefail
REAL_GIT=/usr/local/libexec/rakazo/git
if [[ "${RAKAZO_GITHUB_BROKER_URL:-}" == "" || "${RAKAZO_GITHUB_BROKER_RUN_TOKEN:-}" == "" ]]; then
  exec "$REAL_GIT" "$@"
fi
# Skip global options so `git -c … clone` and `git -C dir fetch` still go through the broker.
# Config overrides are dropped: the broker supplies the credentials.
args=("$@")
i=0
cwd="$PWD"
while (( i < ${#args[@]} )); do
  case "${args[i]}" in
    -c) i=$((i + 2)) ;;
    -C)
      cwd="$(cd "$cwd" && cd "${args[i + 1]:-}" && pwd)" || exec "$REAL_GIT" "$@"
      i=$((i + 2))
      ;;
    --no-pager | -P) i=$((i + 1)) ;;
    *) break ;;
  esac
done
case "${args[i]:-}" in
  push | fetch | pull | clone | ls-remote)
    payload="$(python3 -c 'import json,sys; print(json.dumps({"argv":["git"]+sys.argv[2:],"cwd":sys.argv[1]}))' "$cwd" "${args[@]:i}")"
    exec "$(dirname "$(readlink -f "$0")")/rakazo-broker" v1/git "$payload"
    ;;
esac
exec "$REAL_GIT" "$@"
