name: Build release binaries

on:
  release:
    types: [published]
  workflow_dispatch:

permissions:
  contents: write

jobs:
  build:
    strategy:
      fail-fast: false
      matrix:
        include:
          - target: x86_64-unknown-linux-gnu
            os: ubuntu-latest
          - target: aarch64-unknown-linux-gnu
            os: ubuntu-latest
          - target: x86_64-apple-darwin
            os: macos-14
          - target: aarch64-apple-darwin
            os: macos-latest

    runs-on: ${{ matrix.os }}

    steps:
    - uses: actions/checkout@v4

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

    - uses: Swatinem/rust-cache@v2
      with:
        key: ${{ matrix.target }}

    - name: Install FUSE dependencies (Linux)
      if: runner.os == 'Linux'
      run: |
        sudo apt-get update
        sudo apt-get install -y libfuse3-dev

    - name: Install cross (aarch64-linux)
      if: matrix.target == 'aarch64-unknown-linux-gnu'
      run: cargo install cross --git https://github.com/cross-rs/cross

    - name: Install macFUSE (macOS)
      if: runner.os == 'macOS'
      run: brew install macfuse

    - name: Build (cross)
      if: matrix.target == 'aarch64-unknown-linux-gnu'
      run: cross build --release --target ${{ matrix.target }}

    - name: Build (native)
      if: matrix.target != 'aarch64-unknown-linux-gnu'
      run: cargo build --release --target ${{ matrix.target }}
      env:
        PKG_CONFIG_ALLOW_CROSS: ${{ matrix.target == 'x86_64-apple-darwin' && '1' || '' }}

    - name: Package
      shell: bash
      run: |
        cd target/${{ matrix.target }}/release
        tar czf ../../../cvmfs-cli-${{ matrix.target }}.tar.gz cvmfs-cli
        cd ../../..

    - name: Upload to release
      if: github.event_name == 'release'
      env:
        GH_TOKEN: ${{ github.token }}
      run: gh release upload ${{ github.event.release.tag_name }} cvmfs-cli-${{ matrix.target }}.tar.gz
