name: Release
on:
  push:
    branches:
      - main

permissions:
  contents: write
  pull-requests: write
  id-token: write

jobs:
  release-plz:
    name: Release-Plz (Versioning & Crates.io)
    runs-on: ubuntu-latest
    outputs:
      releases: ${{ steps.rp.outputs.releases }}
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Install Rust
        uses: dtolnay/rust-toolchain@stable

      - name: Run Release-Plz
        id: rp
        uses: MarcoIeni/release-plz-action@v0.5
        env:
          GITHUB_TOKEN: ${{ secrets.RELEASE_PLZ_TOKEN }}
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}

  # This job only runs if release-plz actually created a new git tag
  build-and-upload-assets:
    name: Build Binaries (cargo-dist)
    needs: release-plz
    if: ${{ needs.release-plz.outputs.releases != '[]' }}
    strategy:
      matrix:
        include:
          - os: ubuntu-latest
            target: x86_64-unknown-linux-gnu
          - os: macos-latest
            target: aarch64-apple-darwin
          - os: windows-latest
            target: x86_64-pc-windows-msvc
    runs-on: ${{ matrix.os }}
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

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

      - name: Install cargo-dist
        run: curl --proto '=https' --tlsv1.2 -LsSf https://github.com/axodotdev/cargo-dist/releases/latest/download/cargo-dist-installer.sh | sh

      - name: Run cargo-dist build
        run: cargo dist build --target ${{ matrix.target }} --artifacts=local --allow-all --output-format json > dist-manifest.json

      - name: Upload to GitHub Release
        uses: softprops/action-gh-release@v2
        with:
          # This grabs the tag created by release-plz
          tag_name: ${{ fromJson(needs.release-plz.outputs.releases)[0].tag }}
          files: target/dist/*
