name: SLSA Verify

on:
  workflow_run:
    workflows: ["Release"]
    types: [completed]
    branches: [main]

permissions:
  contents: read
  id-token: write

jobs:
  verify:
    runs-on: ubuntu-latest
    env:
          GH_TOKEN: ${{ github.token }}
    if: ${{ github.event.workflow_run.conclusion == 'success' }}
    steps:
      - uses: actions/checkout@v4

      - name: Get latest release tag
        id: latest_release
        run: |
          release=$(gh release list --limit 1 --repo ${{ github.repository }} \
            --json tagName --jq '.[0].tagName')
          if [ -n "$release" ]; then
            echo "tag=$release" >> $GITHUB_OUTPUT
            echo "has_release=true" >> $GITHUB_OUTPUT
          else
            echo "tag=" >> $GITHUB_OUTPUT
            echo "has_release=false" >> $GITHUB_OUTPUT
          fi

        env:
          GH_TOKEN: ${{ github.token }}

      - name: Download release artifacts
        if: steps.latest_release.outputs.has_release == 'true'
        run: |
          gh release download "${{ steps.latest_release.outputs.tag }}" \
            --repo ${{ github.repository }} \
            --pattern "*.tar.gz" \
            --dir ./artifacts
        env:
          GH_TOKEN: ${{ github.token }}

      - name: Download SLSA provenance
        if: steps.latest_release.outputs.has_release == 'true'
        run: |
          gh release download "${{ steps.latest_release.outputs.tag }}" \
            --repo ${{ github.repository }} \
            --pattern "*.intoto.jsonl" \
            --dir ./artifacts
        env:
          GH_TOKEN: ${{ github.token }}

      - name: Install SLSA verifier
        uses: slsa-framework/slsa-verifier/actions/installer@v2.7.1

      - name: Verify SLSA provenance
        if: steps.latest_release.outputs.has_release == 'true'
        run: |
          ls -la ./artifacts
          FILENAME=$(ls ./artifacts/*.tar.gz | head -1)
          PROVENANCE=$(ls ./artifacts/*.intoto.jsonl | head -1)
          slsa-verifier verify-artifact "$FILENAME" \
            --provenance-path "$PROVENANCE" \
            --source-uri github.com/${{ github.repository }} \
            --tag-name "${{ steps.latest_release.outputs.tag }}"
