#!/usr/bin/env bash

# Regression test: when github.credential_command invokes a tool that is
# a mise shim (e.g. `gh auth token`), the subprocess must not inherit
# the shims directory in PATH.  Without the fix in get_credential_command_token(),
# the shim calls `mise exec` which re-enters token resolution and spawns
# the same command again infinitely → fork bomb.

# Create a fake "gh" shim that mimics real mise shim behavior:
# it calls `mise exec -- gh "$@"`, which would trigger recursive mise
# resolution if shims are still in PATH.
mkdir -p "$MISE_DATA_DIR/shims"
cat >"$MISE_DATA_DIR/shims/gh" <<'SHIM'
#!/bin/sh
# If this shim is invoked, the recursion guard failed.
# A real shim would call `mise exec -- gh "$@"` here,
# but for test safety we just print a marker and exit.
echo SHIM_INVOKED >&2
exit 1
SHIM
chmod +x "$MISE_DATA_DIR/shims/gh"

# Create a real "gh" that the credential_command should find
# (after shims are stripped from PATH).
realdir="$HOME/realbin"
mkdir -p "$realdir"
cat >"$realdir/gh" <<'REAL'
#!/bin/sh
# Simulate `gh auth token` returning a token
echo "ghp_test_token_12345"
REAL
chmod +x "$realdir/gh"

# Put shims BEFORE the real binary in PATH
export PATH="$MISE_DATA_DIR/shims:$realdir:$PATH"

# Configure credential_command and a github: backend tool.
# The github: backend calls the GitHub API to list releases, which triggers
# resolve_token() → get_credential_command_token("gh auth token").
# The dummy plugin does NOT make GitHub API calls, so we must use a
# backend that does (github:).
cat >mise.toml <<'EOF'
[settings.github]
credential_command = "gh auth token"

[tools]
"github:jdx/mise" = "latest"
EOF
mise trust --yes

# Clear cache to force a fresh GitHub API call (and thus token resolution)
mise cache clear

# `mise ls-remote` for a github: tool triggers GitHub API → resolve_token()
# → credential_command → `gh auth token`.
# Without the fix: shim invoked → fork bomb (timeout).
# With the fix: real gh found → returns token, no recursion.
# The command may fail (no real GitHub token) but must not hang or invoke the shim.
run_with_timeout 15 mise ls-remote "github:jdx/mise" 2>/tmp/credential_test_stderr || true

# The shim marker must NOT appear in stderr
assert_not_contains "cat /tmp/credential_test_stderr" "SHIM_INVOKED"
