# This workflow is based on the one from the `cargo-release` crate
# which can be installed with `cargo install cargo-release`

# # Dry run first to see what will happen
# `cargo release patch`

# # Execute the release
# `cargo release patch --execute`

name: Release

on:
  push:
    tags:
      - 'v*.*.*'

permissions:
  contents: write
  id-token: write
  attestations: write

env:
  CARGO_TERM_COLOR: always

jobs:
  create-release:
    name: Create Release
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Create Release
        uses: softprops/action-gh-release@v2
        with:
          generate_release_notes: true
          draft: false
          prerelease: false

  build-assets:
    name: Build Assets
    needs: create-release
    runs-on: ${{ matrix.os }}
    strategy:
      fail-fast: false
      matrix:
        include:
          - os: ubuntu-latest
            target: x86_64-unknown-linux-gnu
            asset_name: impa-linux-amd64
            binary_name: impa
          - os: macos-latest
            target: x86_64-apple-darwin
            asset_name: impa-macos-amd64
            binary_name: impa
          - os: windows-latest
            target: x86_64-pc-windows-msvc
            asset_name: impa-windows-amd64.exe
            binary_name: impa.exe

    steps:
      - uses: actions/checkout@v4

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

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

      - name: Rename Binary
        shell: bash
        run: |
          cp target/${{ matrix.target }}/release/${{ matrix.binary_name }} ${{ matrix.asset_name }}

      - name: Attest Build Provenance
        uses: actions/attest-build-provenance@v1
        with:
          subject-path: ${{ matrix.asset_name }}

      - name: Upload Release Asset
        uses: softprops/action-gh-release@v2
        with:
          files: ${{ matrix.asset_name }}

  publish-crate:
    name: Publish to Crates.io
    needs: build-assets
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Install Rust
        uses: dtolnay/rust-toolchain@stable
      - name: Publish to Crates.io
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
        run: cargo publish
