name: release

on:
  push:
    tags:
      - "v*"

permissions:
  contents: write

jobs:
  prepare-release:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6

      - name: Ensure release exists
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          gh release view "${GITHUB_REF_NAME}" --repo "${GITHUB_REPOSITORY}" >/dev/null 2>&1 || \
            gh release create "${GITHUB_REF_NAME}" \
              --repo "${GITHUB_REPOSITORY}" \
              --verify-tag \
              --title "${GITHUB_REF_NAME}" \
              --notes ""

  build:
    needs: prepare-release
    strategy:
      fail-fast: false
      matrix:
        include:
          - os: ubuntu-latest
            target: x86_64-unknown-linux-gnu
          - os: macos-latest
            target: x86_64-apple-darwin
          - os: macos-latest
            target: aarch64-apple-darwin
    runs-on: ${{ matrix.os }}
    steps:
      - uses: actions/checkout@v6

      - uses: dtolnay/rust-toolchain@stable
        with:
          targets: ${{ matrix.target }}

      - name: Build
        run: cargo build --release --target ${{ matrix.target }} --locked

      - name: Assemble archive
        id: archive
        run: |
          ./scripts/package-release.sh \
            --version "${GITHUB_REF_NAME}" \
            --target "${{ matrix.target }}" >> "${GITHUB_OUTPUT}"

      - name: Upload to release
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          gh release upload "${GITHUB_REF_NAME}" \
            --repo "${GITHUB_REPOSITORY}" \
            "${{ steps.archive.outputs.archive }}" \
            "${{ steps.archive.outputs.checksum }}" \
            --clobber
