name: OpenWrt Cross-Compile

on:
  push:
    tags:
      - 'v*'
  workflow_dispatch:

env:
  CARGO_TERM_COLOR: always
  MAX_SIZE_MB: 5

jobs:
  cross-compile:
    name: Cross-compile (${{ matrix.target }})
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        target:
          - x86_64-unknown-linux-musl
          - armv7-unknown-linux-musleabihf
          - aarch64-unknown-linux-musl

    steps:
      - uses: actions/checkout@v4

      - name: Install Rust toolchain
        uses: dtolnay/rust-toolchain@stable

      - name: Install cargo-zigbuild and zig
        run: |
          pip3 install ziglang
          cargo install cargo-zigbuild

      - name: Add target
        run: rustup target add ${{ matrix.target }}

      - name: Build (size-optimised)
        env:
          CARGO_PROFILE_RELEASE_OPT_LEVEL: s
          CARGO_PROFILE_RELEASE_LTO: 'true'
          CARGO_PROFILE_RELEASE_CODEGEN_UNITS: '1'
          CARGO_PROFILE_RELEASE_STRIP: symbols
        run: |
          cargo zigbuild --release --target ${{ matrix.target }} --bin qpc-server

      - name: Check binary size
        run: |
          BINARY="target/${{ matrix.target }}/release/qpc-server"
          SIZE=$(stat -c%s "$BINARY")
          SIZE_MB=$(echo "scale=2; $SIZE / 1048576" | bc)
          echo "Binary size: ${SIZE_MB} MB"
          MAX_BYTES=$(( ${{ env.MAX_SIZE_MB }} * 1048576 ))
          if [ "$SIZE" -gt "$MAX_BYTES" ]; then
            echo "::error::Binary exceeds ${MAX_SIZE_MB} MB limit (${SIZE_MB} MB)"
            exit 1
          fi

      - name: Upload artifact
        uses: actions/upload-artifact@v4
        with:
          name: qpc-server-${{ matrix.target }}
          path: target/${{ matrix.target }}/release/qpc-server
          retention-days: 30
