#!/usr/bin/env bash

export MISE_OFFLINE=1
export MISE_SOPS_ROPS=0
export MISE_SOPS_STRICT=1
unset MISE_SOPS_AGE_KEY MISE_SOPS_AGE_KEY_FILE SOPS_AGE_KEY SOPS_AGE_KEY_FILE

mkdir -p "$PWD/installed/bin" "$PWD/fallback" "$PWD/commands" "$MISE_DATA_DIR/shims"
cat >"$PWD/installed/bin/sops" <<'EOF'
#!/usr/bin/env bash
cat >/dev/null
printf '{"SECRET":"installed"}\n'
EOF
cat >"$PWD/fallback/sops" <<'EOF'
#!/usr/bin/env bash
cat >/dev/null
printf '{"SECRET":"fallback"}\n'
EOF
chmod +x "$PWD/installed/bin/sops" "$PWD/fallback/sops"

# Keep one version installed while the project asks for a different version.
mise link sops@0.0.1 "$PWD/installed"

# Use a bounded probe instead of a real shim: a regression must fail without
# recursively spawning mise and exhausting the test runner.
rm -f "$MISE_DATA_DIR/shims/sops"
cat >"$MISE_DATA_DIR/shims/sops" <<'EOF'
#!/usr/bin/env bash
touch "$HOME/sops-shim-invoked"
exit 99
EOF
chmod +x "$MISE_DATA_DIR/shims/sops"
mise_bin="$(command -v mise)"
ln -s "$mise_bin" "$PWD/commands/mise"
for utility in bash cat touch; do
  ln -s "$(command -v "$utility")" "$PWD/commands/$utility"
done
export SOPS_TEST_PATH="$MISE_DATA_DIR/shims:$PWD/fallback:$PWD/commands"

cat >secrets.json <<'EOF'
{"SECRET":"ENC[fake]","sops":{"version":"3.9.4"}}
EOF

# An installed configured version still takes precedence over PATH.
cat >mise.toml <<'EOF'
[tools]
sops = "0.0.1"

[env]
_.file = "secrets.json"
EOF
assert_contains "PATH=\"$SOPS_TEST_PATH\" mise env" "export SECRET=installed"
assert "test ! -e \"$HOME/sops-shim-invoked\""

cat >mise.toml <<'EOF'
[tools]
sops = "0.0.0"

[env]
_.file = "secrets.json"
EOF

# Missing configured version: ignore the shim and use the real PATH fallback.
assert_contains "PATH=\"$SOPS_TEST_PATH\" mise env" "export SECRET=fallback"
assert "test ! -e \"$HOME/sops-shim-invoked\""

# With only the shim available, preserve strict/non-strict missing-CLI behavior.
mv fallback/sops fallback/sops-disabled
assert_fail "PATH=\"$SOPS_TEST_PATH\" mise env"
assert_contains "PATH=\"$SOPS_TEST_PATH\" mise env 2>&1 || true" "sops command not found"
assert "test ! -e \"$HOME/sops-shim-invoked\""
export MISE_SOPS_STRICT=0
assert_not_contains "PATH=\"$SOPS_TEST_PATH\" mise env" "SECRET"
assert "test ! -e \"$HOME/sops-shim-invoked\""

# Without a configured version, the PATH lookup must still skip the shim.
mv fallback/sops-disabled fallback/sops
cat >mise.toml <<'EOF'
[env]
_.file = "secrets.json"
EOF
export MISE_SOPS_STRICT=1
assert_contains "PATH=\"$SOPS_TEST_PATH\" mise env" "export SECRET=fallback"
assert "test ! -e \"$HOME/sops-shim-invoked\""
