name: Release

on:
  push:
    branches:
      - master

jobs:
  release-plz-release:
    name: Release-plz release
    runs-on: ubuntu-latest
    permissions:
      contents: write
      pull-requests: read
    outputs:
      releases_created: ${{ steps.release.outputs.releases_created }}
      tag: ${{ steps.get-tag.outputs.tag }}
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
          persist-credentials: false

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

      - name: Run release-plz
        id: release
        uses: release-plz/action@v0.5
        with:
          command: release
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}

      - name: Get release tag
        id: get-tag
        if: steps.release.outputs.releases_created == 'true'
        run: echo "tag=${{ fromJSON(steps.release.outputs.releases)[0].tag }}" >> "$GITHUB_OUTPUT"

  release-plz-pr:
    name: Release-plz PR
    runs-on: ubuntu-latest
    permissions:
      contents: write
      pull-requests: write
    concurrency:
      group: release-plz-${{ github.ref }}
      cancel-in-progress: false
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
          persist-credentials: false

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

      - name: Run release-plz
        uses: release-plz/action@v0.5
        with:
          command: release-pr
        env:
          GITHUB_TOKEN: ${{ secrets.RELEASE_PLZ_TOKEN }}
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}

  upload-binaries:
    name: Upload ${{ matrix.target }}
    needs: release-plz-release
    if: needs.release-plz-release.outputs.releases_created == 'true'
    runs-on: ${{ matrix.os }}
    permissions:
      contents: write
    strategy:
      fail-fast: false
      matrix:
        include:
          - target: x86_64-unknown-linux-gnu
            os: ubuntu-latest
          - target: aarch64-unknown-linux-gnu
            os: ubuntu-latest
          - target: aarch64-apple-darwin
            os: macos-latest
    steps:
      - uses: actions/checkout@v4
        with:
          ref: ${{ needs.release-plz-release.outputs.tag }}

      - uses: taiki-e/setup-cross-toolchain-action@v1
        with:
          target: ${{ matrix.target }}
        if: matrix.target == 'aarch64-unknown-linux-gnu'

      - uses: taiki-e/upload-rust-binary-action@v1
        with:
          bin: auberge
          target: ${{ matrix.target }}
          ref: refs/tags/${{ needs.release-plz-release.outputs.tag }}
          checksum: sha256
          token: ${{ secrets.GITHUB_TOKEN }}
