name: Release

on:
  push:
    tags:
      - "v*"

permissions:
  contents: write

jobs:
  build:
    strategy:
      matrix:
        include:
          - target: x86_64-unknown-linux-gnu
            os: ubuntu-latest
          - target: x86_64-apple-darwin
            os: macos-latest
          - target: aarch64-apple-darwin
            os: macos-latest
    runs-on: ${{ matrix.os }}
    steps:
      - uses: actions/checkout@v4

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

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

      - name: Package
        run: |
          cd target/${{ matrix.target }}/release
          tar czf ../../../crmux-${{ matrix.target }}.tar.gz crmux
          cd ../../..

      - name: Upload artifact
        uses: actions/upload-artifact@v4
        with:
          name: crmux-${{ matrix.target }}
          path: crmux-${{ matrix.target }}.tar.gz

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

      - name: Extract changelog for this version
        id: changelog
        run: |
          version="${GITHUB_REF_NAME#v}"
          body=$(awk "/^## ${version}\$/{ found=1; next } /^## /{ if(found) exit } found{ print }" CHANGELOG.md)
          {
            echo "body<<CHANGELOG_EOF"
            echo "$body"
            echo "CHANGELOG_EOF"
          } >> "$GITHUB_OUTPUT"

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

      - name: Create GitHub Release
        uses: softprops/action-gh-release@v2
        with:
          body: ${{ steps.changelog.outputs.body }}
          files: crmux-*.tar.gz
