name: Release

on:
  push:
    tags:
      - "v*"

env:
  CARGO_TERM_COLOR: always

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: false

jobs:
  build-release:
    name: Build Release
    timeout-minutes: 45
    strategy:
      fail-fast: false
      matrix:
        include:
          - target: x86_64-apple-darwin
            os: macos-latest
          - target: aarch64-apple-darwin
            os: macos-latest
          - target: x86_64-unknown-linux-gnu
            os: ubuntu-latest
          - target: aarch64-unknown-linux-gnu
            os: ubuntu-latest
    runs-on: ${{ matrix.os }}

    steps:
      - uses: actions/checkout@v4

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

      - name: Install cross-compilation tools (Linux ARM64)
        if: matrix.target == 'aarch64-unknown-linux-gnu'
        run: |
          sudo apt-get update
          sudo apt-get install -y gcc-aarch64-linux-gnu g++-aarch64-linux-gnu

      - name: Cache cargo registry
        uses: actions/cache@v4
        with:
          path: ~/.cargo/registry
          key: ${{ runner.os }}-${{ matrix.target }}-cargo-registry-${{ hashFiles('**/Cargo.lock') }}

      - name: Cache cargo index
        uses: actions/cache@v4
        with:
          path: ~/.cargo/git
          key: ${{ runner.os }}-${{ matrix.target }}-cargo-index-${{ hashFiles('**/Cargo.lock') }}

      - name: Cache cargo build
        uses: actions/cache@v4
        with:
          path: target
          key: ${{ runner.os }}-${{ matrix.target }}-cargo-build-target-${{ hashFiles('**/Cargo.lock') }}

      - name: Build release
        run: cargo build --release --target ${{ matrix.target }}
        env:
          CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER: aarch64-linux-gnu-gcc
          CC_aarch64_unknown_linux_gnu: aarch64-linux-gnu-gcc
          CXX_aarch64_unknown_linux_gnu: aarch64-linux-gnu-g++

      - name: Create release archive
        run: |
          mkdir -p release
          cp target/${{ matrix.target }}/release/ggen release/
          tar -czf ggen-${{ matrix.target }}.tar.gz -C release ggen
          sha256sum ggen-${{ matrix.target }}.tar.gz > ggen-${{ matrix.target }}.tar.gz.sha256

      - name: Upload Release Assets
        uses: softprops/action-gh-release@v2
        with:
          files: |
            ggen-${{ matrix.target }}.tar.gz
            ggen-${{ matrix.target }}.tar.gz.sha256
          fail_on_unmatched_files: true
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

  # Note: Homebrew formula update is done manually
  # SHA256 checksums are available in release assets as *.sha256 files
