#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd -P)"
# GIT_CONFIG_VALUE_1 below is a `!`-prefixed credential.helper, which git
# re-parses through `sh -c`: a space in the install path breaks the command and
# a `$(...)` in it executes. Quoting is not enough — allowlist the characters.
case "$SCRIPT_DIR" in
  *[!A-Za-z0-9._/-]*) echo "bot-env: install path contains an unsafe character; refusing to emit a shell-evaluated credential helper" >&2; exit 1 ;;
esac

ORG="acme"
BOT_NAME="${ORG}-agent[bot]"
BOT_EMAIL="<BOT_UID>+${ORG}-agent[bot]@users.noreply.github.com"
ORG_LC="$(printf '%s' "$ORG" | tr '[:upper:]' '[:lower:]')"

verdict=personal
ssh_prefixes=""
rc=0
git rev-parse --is-inside-work-tree >/dev/null 2>&1 || rc=$?
if [ "$rc" -eq 0 ]; then
  raw_remotes="$(mktemp)"
  worktree_remotes="$(mktemp)"
  trap 'rm -f "$raw_remotes" "$worktree_remotes"' EXIT
  remote_rc=0
  git config --local --null --get-regexp '^remote\..*\.(url|pushurl)$' >"$raw_remotes" 2>/dev/null || remote_rc=$?
  if [ "$remote_rc" -eq 1 ] && [ ! -s "$raw_remotes" ]; then
    remote_rc=0
  fi
  if [ "$remote_rc" -eq 0 ]; then
    worktree_enabled=""
    worktree_flag_rc=0
    worktree_enabled="$(git config --local --bool --get extensions.worktreeConfig 2>/dev/null)" || worktree_flag_rc=$?
    if [ "$worktree_flag_rc" -eq 0 ] && [ "$worktree_enabled" = true ]; then
      worktree_rc=0
      git config --worktree --null --get-regexp '^remote\..*\.(url|pushurl)$' >"$worktree_remotes" 2>/dev/null || worktree_rc=$?
      if [ "$worktree_rc" -eq 0 ]; then
        cat "$worktree_remotes" >>"$raw_remotes"
      elif [ "$worktree_rc" -ne 1 ] || [ -s "$worktree_remotes" ]; then
        remote_rc="$worktree_rc"
      fi
    elif [ "$worktree_flag_rc" -ne 0 ] && [ "$worktree_flag_rc" -ne 1 ]; then
      remote_rc="$worktree_flag_rc"
    fi
  fi
  if [ "$remote_rc" -eq 0 ]; then
    if [ ! -s "$raw_remotes" ]; then
      verdict=bot
      echo "bot-env: no raw remote URLs in $PWD; ambiguous, using the bot identity" >&2
    else
      empty_remote=0
      while IFS= read -r -d '' remote_record; do
        case "$remote_record" in
          *$'\n'*) url="${remote_record#*$'\n'}" ;;
          *) empty_remote=1; continue ;;
        esac
        if [ -z "$url" ]; then
          empty_remote=1
          continue
        fi
        prefix=""
        case "$url" in
          *://*)
            scheme="${url%%://*}"; rest="${url#*://}"; auth="${rest%%/*}"; host="${auth#*@}"; host="${host%%:*}"; path="${rest#*/}"
            case "$scheme" in
              [Hh][Tt][Tt][Pp][Ss]) ;;
              *) prefix="${scheme}://${auth}/${path%%/*}/" ;;
            esac
            ;;
          *)
            rest="${url#*@}"; host="${rest%%:*}"; path="${rest#*:}"
            prefix="${url%%:*}:${path%%/*}/"
            ;;
        esac
        host_lc="$(printf '%s' "$host" | tr '[:upper:]' '[:lower:]')"
        org_segment_lc="$(printf '%s' "${path%%/*}" | tr '[:upper:]' '[:lower:]')"
        if [ "$host_lc" = github.com ] && [ "$org_segment_lc" = "$ORG_LC" ]; then
          verdict=bot
          case "$prefix" in
            "") ;;
            "git@github.com:${ORG}/") ;;
            *"'"*) echo "bot-env: matched remote prefix contains a single quote in $PWD; refusing to run with undetermined identity" >&2; exit 1 ;;
            *)
              case "$ssh_prefixes" in
                *"|${prefix}|"*) ;;
                *) ssh_prefixes="${ssh_prefixes}|${prefix}|" ;;
              esac
              ;;
          esac
        fi
      done <"$raw_remotes"
      if [ "$empty_remote" -eq 1 ] && [ "$verdict" != bot ]; then
        verdict=bot
        echo "bot-env: empty raw remote URL in $PWD; ambiguous, using the bot identity" >&2
      fi
    fi
  else
    verdict=bot
    echo "bot-env: raw remote query failed in $PWD; using the bot identity" >&2
  fi
elif [ "$rc" -ne 128 ]; then
  verdict=bot
  echo "bot-env: git probe failed (exit $rc) in $PWD; ambiguous, using the bot identity" >&2
fi

if [ "$verdict" != bot ]; then
  cat <<'EOF'
unset GIT_AUTHOR_NAME GIT_AUTHOR_EMAIL GIT_COMMITTER_NAME GIT_COMMITTER_EMAIL
unset GIT_CONFIG_COUNT
unset GH_TOKEN
EOF
  # In a reused shell, bot-env inherits any exported GIT_CONFIG_* vars, so it
  # can enumerate exactly what exists and emit portable unset lines for them.
  for v in $(compgen -v | grep -E '^GIT_CONFIG_(KEY|VALUE)_[0-9]+$' || true); do
    echo "unset $v"
  done
  exit 0
fi

# A mint that "succeeds" with empty output is as dangerous as a crash: gh treats
# an empty GH_TOKEN as unset and falls back to the personal stored credentials.
token="$("$SCRIPT_DIR/bot-token")" || token=""
[ -n "$token" ] || token="BOT-TOKEN-MINT-FAILED"

cat <<EOF
export GIT_AUTHOR_NAME='${BOT_NAME}'
export GIT_AUTHOR_EMAIL='${BOT_EMAIL}'
export GIT_COMMITTER_NAME='${BOT_NAME}'
export GIT_COMMITTER_EMAIL='${BOT_EMAIL}'
export GIT_CONFIG_KEY_0='credential.helper'
export GIT_CONFIG_VALUE_0=''
export GIT_CONFIG_KEY_1='credential.helper'
export GIT_CONFIG_VALUE_1='!${SCRIPT_DIR}/git-credential-bot'
export GIT_CONFIG_KEY_2='url.https://github.com/${ORG}/.insteadOf'
export GIT_CONFIG_VALUE_2='git@github.com:${ORG}/'
export GIT_CONFIG_KEY_3='commit.gpgsign'
export GIT_CONFIG_VALUE_3='false'
EOF

idx=4
if [ -n "$ssh_prefixes" ]; then
  while IFS= read -r p; do
    [ -n "$p" ] || continue
    cat <<EOF
export GIT_CONFIG_KEY_${idx}='url.https://github.com/${ORG}/.insteadOf'
export GIT_CONFIG_VALUE_${idx}='${p}'
EOF
    idx=$((idx + 1))
  done <<EOF2
$(printf '%s' "$ssh_prefixes" | tr '|' '\n')
EOF2
fi

cat <<EOF
export GIT_CONFIG_COUNT=${idx}
export GH_TOKEN='${token}'
EOF
