name: Release

on:
  push:
    tags:
      - "v*"

permissions:
  contents: write

jobs:
  build:
    name: Build {% raw %}${{ matrix.target }}{% endraw %}
    runs-on: {% raw %}${{ matrix.os }}{% endraw %}
    strategy:
      matrix:
        include:
          - target: x86_64-unknown-linux-gnu
            os: ubuntu-latest
            binary: {{project-name}}
            asset: {{project-name}}-x86_64-linux
          - target: aarch64-unknown-linux-gnu
            os: ubuntu-latest
            binary: {{project-name}}
            asset: {{project-name}}-aarch64-linux
    steps:
      - uses: actions/checkout@v4

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

      - uses: Swatinem/rust-cache@v2

      - name: Install cross
        run: cargo install cross --locked

      - name: Build release binary
        run: cross build --release --target {% raw %}${{ matrix.target }}{% endraw %}

      - name: Rename binary
        run: cp target/{% raw %}${{ matrix.target }}/release/${{ matrix.binary }} ${{ matrix.asset }}{% endraw %}

      - name: Upload artifact
        uses: actions/upload-artifact@v4
        with:
          name: {% raw %}${{ matrix.asset }}{% endraw %}
          path: {% raw %}${{ matrix.asset }}{% endraw %}

  release:
    name: Create GitHub Release
    needs: build
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Download all artifacts
        uses: actions/download-artifact@v4
        with:
          path: artifacts
          merge-multiple: true

      - name: Extract changelog notes for tag
        id: changelog
        run: |
          {% raw %}VERSION=${GITHUB_REF#refs/tags/v}
          NOTES=$(awk "/## \[$VERSION\]/{flag=1; next} /## \[/{flag=0} flag" CHANGELOG.md)
          {
            echo "notes<<EOF"
            echo "$NOTES"
            echo "EOF"
          } >> "$GITHUB_OUTPUT"{% endraw %}

      - name: Publish GitHub Release
        uses: softprops/action-gh-release@v2
        with:
          body: {% raw %}${{ steps.changelog.outputs.notes }}{% endraw %}
          files: artifacts/*
