#!/usr/bin/env bash
set -euo pipefail

# A [plugins] entry without a type prefix that names a signed packslip archive
# installs as a vfox plugin, not as an asdf plugin cloned with Git.
export MISE_MINIMUM_RELEASE_AGE=0
# The fixture server stands in for GitHub; the real mise-versions would answer
# for the real repository instead.
export MISE_USE_VERSIONS_HOST=0
export MISE_DATA_DIR="$PWD/data"
unset GITHUB_TOKEN GITHUB_API_TOKEN MISE_GITHUB_TOKEN
mkdir server-state
python3 "$ROOT/test/fixtures/packslip-vfox/server.py" "$PWD/server-state" &
server_pid=$!
trap 'kill "$server_pid" 2>/dev/null || true' EXIT
for _ in {1..100}; do
  [[ -f server-state/port ]] && break
  sleep 0.1
done
port=$(cat server-state/port)
export MISE_URL_REPLACEMENTS="{\"https://api.github.com\":\"http://127.0.0.1:$port\",\"https://github.com\":\"http://127.0.0.1:$port\"}"

export GIT_INVOKED_LOG="$PWD/git-invoked"
mkdir no-git
cat >no-git/git <<'EOF'
#!/usr/bin/env bash
echo invoked >> "$GIT_INVOKED_LOG"
exit 1
EOF
chmod +x no-git/git
export PATH="$PWD/no-git:$PATH"

cat >mise.toml <<'EOF'
[plugins]
external-bfs = "packslip:mise-plugins/vfox-bfs#0.1.0-dev.2"
EOF

# Before the plugin is installed, the tool already resolves to vfox.
assert_contains "mise tool external-bfs" "vfox:external-bfs"

# `mise install` installs [plugins] entries from the signed archive.
mise install
plugin="$MISE_DATA_DIR/plugins/external-bfs"
assert "test -f '$plugin/metadata.lua'"
assert_contains "cat '$plugin/.mise-packslip-plugin.json'" '"version": "0.1.0-dev.2"'
assert_contains "mise plugins ls --urls" "packslip:github.com/mise-plugins/vfox-bfs#0.1.0-dev.2"
assert "test ! -e git-invoked"

# An explicit non-vfox prefix cannot install a packslip archive, and says so
# instead of handing the archive to Git.
cat >mise.toml <<'EOF'
[plugins]
"asdf:asdf-bfs" = "packslip:mise-plugins/vfox-bfs#0.1.0-dev.2"
EOF
assert_fail_contains "mise install" "packslip plugin sources require the vfox plugin type"
assert "test ! -e git-invoked"
