name: Release

on:
  push:
    tags:
      - "v*"

permissions:
  contents: write

env:
  CARGO_TERM_COLOR: always

jobs:
  build:
    name: Build (${{ matrix.target }})
    runs-on: ${{ matrix.os }}
    strategy:
      fail-fast: false
      matrix:
        include:
          - target: aarch64-apple-darwin
            os: macos-14            # Apple Silicon runner
            cross: false

          - target: x86_64-apple-darwin
            os: macos-13            # Intel runner
            cross: false

          - target: x86_64-unknown-linux-gnu
            os: ubuntu-latest
            cross: false

          - target: aarch64-unknown-linux-gnu
            os: ubuntu-latest
            cross: true

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

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

      - name: Install cross (Linux ARM64)
        if: matrix.cross
        run: cargo install cross --locked

      - name: Build release binary
        run: |
          if [ "${{ matrix.cross }}" = "true" ]; then
            cross build --release --target ${{ matrix.target }}
          else
            cargo build --release --target ${{ matrix.target }}
          fi

      - name: Package tarball
        run: |
          TAG="${GITHUB_REF_NAME}"
          TARBALL="railguard-${TAG}-${{ matrix.target }}.tar.gz"
          cp "target/${{ matrix.target }}/release/railguard" railguard
          tar -czf "$TARBALL" railguard
          echo "TARBALL=$TARBALL" >> "$GITHUB_ENV"

      - name: Upload artifact
        uses: actions/upload-artifact@v4
        with:
          name: railguard-${{ matrix.target }}
          path: ${{ env.TARBALL }}

  release:
    name: Create GitHub Release
    needs: build
    runs-on: ubuntu-latest
    steps:
      - name: Download all artifacts
        uses: actions/download-artifact@v4
        with:
          path: artifacts
          merge-multiple: true

      - name: List artifacts
        run: ls -lh artifacts/

      - name: Create release
        uses: softprops/action-gh-release@v2
        with:
          generate_release_notes: true
          files: artifacts/*.tar.gz
