name: Release Binaries
on:
  release:
    types: [published]

jobs:
  build:
    name: Build ${{ matrix.target }}
    runs-on: ${{ matrix.os }}

    permissions:
      contents: write

    strategy:
      matrix:
        include:
          - target: x86_64-unknown-linux-gnu
            os: ubuntu-latest
            archive: tar.gz
          - target: aarch64-unknown-linux-gnu
            os: ubuntu-latest
            archive: tar.gz
          - target: x86_64-apple-darwin
            os: macos-latest
            archive: tar.gz
          - target: aarch64-apple-darwin
            os: macos-latest
            archive: tar.gz
          - target: x86_64-pc-windows-msvc
            os: windows-latest
            archive: zip

    steps:
      - name: Checkout the code
        uses: actions/checkout@v6

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

      - name: Install cross-compilation tools
        if: matrix.target == 'aarch64-unknown-linux-gnu'
        run: |
          sudo apt-get update
          sudo apt-get install -y gcc-aarch64-linux-gnu
          echo "CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER=aarch64-linux-gnu-gcc" >> "$GITHUB_ENV"

      - name: Set version from tag
        shell: bash
        run: |
          VERSION="${GITHUB_REF_NAME#v}"
          sed -i'' -e "s/^version = .*/version = \"${VERSION}\"/" Cargo.toml

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

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

      - name: Package (unix)
        if: matrix.archive == 'tar.gz'
        shell: bash
        run: |
          ARCHIVE="copc_converter-${{ github.ref_name }}-${{ matrix.target }}.tar.gz"
          tar czf "$ARCHIVE" -C target/${{ matrix.target }}/release copc_converter
          echo "ARCHIVE=$ARCHIVE" >> "$GITHUB_ENV"

      - name: Package (windows)
        if: matrix.archive == 'zip'
        shell: bash
        run: |
          ARCHIVE="copc_converter-${{ github.ref_name }}-${{ matrix.target }}.zip"
          7z a "$ARCHIVE" ./target/${{ matrix.target }}/release/copc_converter.exe
          echo "ARCHIVE=$ARCHIVE" >> "$GITHUB_ENV"

      - name: Upload to release
        uses: softprops/action-gh-release@v2
        with:
          files: ${{ env.ARCHIVE }}
