name: Release binaries

on:
  release:
    types:
      - published
  workflow_dispatch:

permissions: {}

jobs:
  build:
    name: Build for ${{ matrix.target }}
    runs-on: ${{ matrix.runner }}

    strategy:
      matrix:
        include:
          - runner: ubuntu-latest
            target: x86_64-unknown-linux-gnu
          - runner: ubuntu-22.04-arm
            target: aarch64-unknown-linux-gnu
          - runner: macos-latest
            target: x86_64-apple-darwin
          - runner: macos-latest
            target: aarch64-apple-darwin
          - runner: windows-latest
            target: x86_64-pc-windows-msvc
          - runner: windows-latest
            target: aarch64-pc-windows-msvc

    steps:
      - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
        with:
          persist-credentials: false

      - name: Install Rust target
        run: |
          rustup update
          rustup target add "${TARGET}"
        env:
          TARGET: ${{ matrix.target }}
        shell: bash

      - name: Build release
        run: cargo build --release --features hooks --target "${TARGET}"
        env:
          TARGET: ${{ matrix.target }}
        shell: bash

      - name: Archive release
        id: archive-release
        run: ./support/archive-release.sh
        env:
          TARGET: ${{ matrix.target }}
        shell: bash

      - name: Upload artifact
        uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
        with:
          name: artifacts-${{ matrix.target }}
          path: ${{ steps.archive-release.outputs.filename }}
          if-no-files-found: error

  release:
    name: Upload release artifacts
    runs-on: ubuntu-latest
    needs: build
    if: github.event_name == 'release'

    permissions:
      id-token: write # for attestations
      attestations: write # for attestations
      contents: write # for release artifacts

    steps:
      - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
        with:
          persist-credentials: false

      - name: Download artifacts
        uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0
        with:
          pattern: artifacts-*
          path: distrib/
          merge-multiple: true

      - name: List artifacts
        run: ls -l distrib/

      - name: Attest build provenance
        uses: actions/attest-build-provenance@96278af6caaf10aea03fd8d33a09a777ca52d62f # v3.2.0
        with:
          subject-path: "distrib/*"

      - name: Upload to release
        run: gh release upload "${GITHUB_REF_NAME}" distrib/*
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
