name: Release

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

permissions:
  contents: write

jobs:
  build:
    name: Build ${{ matrix.target }}
    runs-on: ${{ matrix.os }}
    strategy:
      fail-fast: false
      matrix:
        include:
          - os: ubuntu-latest
            target: x86_64-unknown-linux-gnu
            artifact_name: shellcast
            asset_name: shellcast-linux-x86_64
          - os: macos-latest
            target: x86_64-apple-darwin
            artifact_name: shellcast
            asset_name: shellcast-macos-x86_64
          - os: macos-latest
            target: aarch64-apple-darwin
            artifact_name: shellcast
            asset_name: shellcast-macos-aarch64

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

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

      - name: Install ALSA dependencies (Linux)
        if: runner.os == 'Linux'
        run: sudo apt-get update && sudo apt-get install -y libasound2-dev

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

      - name: Strip binary
        if: runner.os != 'Windows'
        run: strip target/${{ matrix.target }}/release/${{ matrix.artifact_name }}

      - name: Upload binary
        uses: actions/upload-artifact@v4
        with:
          name: ${{ matrix.asset_name }}
          path: target/${{ matrix.target }}/release/${{ matrix.artifact_name }}

  release:
    name: Create Release
    needs: build
    runs-on: ubuntu-latest
    if: startsWith(github.ref, 'refs/tags/')

    steps:
      - name: Download all artifacts
        uses: actions/download-artifact@v4
        with:
          path: artifacts

      - name: Prepare release binaries
        run: |
          mkdir -p release
          for dir in artifacts/*/; do
            artifact_name=$(basename "$dir")
            mv "$dir/shellcast" "release/$artifact_name"
          done
          ls -la release/

      - name: Create Release
        uses: softprops/action-gh-release@v1
        with:
          files: release/*
          draft: false
          prerelease: false
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
