#!/usr/bin/env bash

# A package can declare GitHub attestations and a second mechanism. When there is no attestation
# to check, `mise lock` has to verify the second one like `mise install` does: an entry with a
# checksum and no provenance is installed later without looking at any signature.

export MISE_LOCKFILE=1
export MISE_AQUA_BAKED_REGISTRY=0
export MISE_USE_VERSIONS_HOST=0
# The attestation API is served over plain HTTP below, where mise refuses to send a token
unset GITHUB_TOKEN GH_TOKEN MISE_GITHUB_TOKEN GITHUB_API_TOKEN

# The API knows the releases and nothing else, so every attestation lookup is answered with 404
mkdir -p server/api/repos/example/tool
cat <<'EOF' >server/api/repos/example/tool/releases
[
  {"tag_name": "2.0.0", "draft": false, "prerelease": false, "created_at": "2026-01-02T00:00:00Z", "assets": []},
  {"tag_name": "1.0.0", "draft": false, "prerelease": false, "created_at": "2026-01-01T00:00:00Z", "assets": []}
]
EOF
printf '#!/bin/sh\necho signed-tool\n' >server/tool-1.0.0
cat <<'EOF' >server/tool-1.0.0.minisig
untrusted comment: mise e2e fixture
RURtaXNldGVzdIKeqlMFXwy85MLDFPMzoQng1nE+UpTU2R3kKjMSau0244K54ehp/Zl7Ew9BLkMJVdh1IQrjyEXNvrfQtsZKLAk=
trusted comment: mise e2e fixture
hw8hHF/+Zk16GrTIh1oO4/HrcyHUATzGE7q556AXxQMntYMc+5Ya5LbhgxTrMu6FSWxZBOVAWYL4EnLSBC+PDQ==
EOF
printf '#!/bin/sh\necho unsigned-tool\n' >server/tool-2.0.0
start_http_server --dir server
export MISE_URL_REPLACEMENTS="{\"https://api.github.com\":\"http://127.0.0.1:$HTTP_PORT/api\"}"

REGISTRY_DIR="$PWD/aqua-registry-local"
mkdir -p "$REGISTRY_DIR"

cat <<EOF >"$REGISTRY_DIR/registry.yaml"
packages:
  - type: http
    repo_owner: example
    repo_name: tool
    url: http://127.0.0.1:$HTTP_PORT/tool-{{.Version}}
    format: raw
    github_artifact_attestations:
      signer_workflow: example/tool/\.github/workflows/release\.yml
    minisign:
      type: http
      url: http://127.0.0.1:$HTTP_PORT/tool-{{.Version}}.minisig
      public_key: RWRtaXNldGVzdJ8gZj14Zasr0dmp5Nuceo6LDCEsajhJYejZfIGqcPOK
    supported_envs:
      - linux
EOF

export MISE_AQUA_REGISTRY_URL="file://$REGISTRY_DIR"

cat <<'EOF' >mise.toml
[tools]
"aqua:example/tool" = "1.0.0"
EOF

mise lock --platform linux-x64
assert_contains "cat mise.lock" "url = \"http://127.0.0.1:$HTTP_PORT/tool-1.0.0\""
assert_contains "cat mise.lock" 'provenance = "minisign"'

# 2.0.0 has no signature either, so nothing vouches for it
rm mise.lock
cat <<'EOF' >mise.toml
[tools]
"aqua:example/tool" = "2.0.0"
EOF

assert_contains "mise lock --platform linux-x64 2>&1" "lock-time provenance verification failed"
if [[ -f mise.lock ]]; then
  assert_not_contains "cat mise.lock" "tool-2.0.0"
fi
