name: build

on:
  push:
    branches: [ "main" ]
  pull_request:
    branches: [ "main" ]
  workflow_dispatch:

env:
  CARGO_TERM_COLOR: always

jobs:
  build:
    runs-on: ${{ matrix.os }}
    strategy:
      matrix:
        os: [ubuntu-latest, macos-latest, windows-latest]
        architecture: [x86_64]
    name: Build on ${{ matrix.os }} for ${{ matrix.architecture }}

    steps:
    - uses: actions/checkout@v4

    - name: Install dependencies on Ubuntu
      if: runner.os == 'Linux'
      run: |
        sudo apt-get update
        sudo apt-get install build-essential cmake perl pkg-config libclang-dev musl-tools -y

    - name: Install dependencies on macOS
      if: runner.os == 'macOS'
      run: |
        brew update
        brew install --formula cmake pkg-config llvm

    - name: Install dependencies on Windows
      if: runner.os == 'Windows'
      run: |
        choco install cmake -y
        choco install strawberryperl -y
        choco install pkgconfiglite -y
        choco install llvm -y
        choco install nasm -y
      shell: cmd

    - name: Build on Windows/macOS
      if: runner.os != 'Linux'
      run: cargo build --release

    - name: Build on Linux
      if: runner.os == 'Linux'
      run: |
        cargo build --release
        docker pull messense/rust-musl-cross:x86_64-musl
        docker run --rm -v "$(pwd)":/home/rust/src messense/rust-musl-cross:x86_64-musl cargo build --release

    - name: Archive build artifacts on macOS
      if: runner.os == 'macOS'
      run: |
        cd target/release
        zip -r ../../build-${{ runner.os }}-${{ matrix.architecture }}.zip *
      working-directory: ${{ github.workspace }}

    - name: Archive build artifacts on Linux
      if: runner.os == 'Linux'
      run: |
        cd target/release
        zip -r ../../build-${{ runner.os }}-${{ matrix.architecture }}.zip *
        cd ../x86_64-unknown-linux-musl/release
        zip -r ../../../build-x86_64-unknown-linux-musl.zip *
      working-directory: ${{ github.workspace }}

    - name: Archive build artifacts on Windows
      if: runner.os == 'Windows'
      shell: pwsh
      run: |
        Compress-Archive -Path 'target\release\*' -DestinationPath "build-${{ runner.os }}-${{ matrix.architecture }}.zip" -CompressionLevel Optimal -Force
      working-directory: ${{ github.workspace }}

    - name: Upload build artifact
      uses: actions/upload-artifact@v4
      with:
        name: build-${{ matrix.os }}-${{ matrix.architecture }}
        path: build-${{ runner.os }}-${{ matrix.architecture }}.zip

    - name: Upload x86_64-unknown-linux-musl Linux build artifact
      if: runner.os == 'Linux'
      uses: actions/upload-artifact@v4
      with:
        name: build-x86_64-unknown-linux-musl
        path: build-x86_64-unknown-linux-musl.zip
