name: Reusable build util

on:
  workflow_call:
    inputs:
      build-system:
        required: true
        type: string
      toolchain:
        required: true
        type: string
      build-args:
        required: true
        type: string
      build-options:
        required: false
        default: ''
        type: string
      upload-artifacts:
        required: false
        default: false
        type: boolean
      upload-metrics:
        required: false
        default: false
        type: boolean
      os:
        required: false
        type: string
        default: 'ubuntu-latest'

jobs:
  family:
    runs-on: ${{ inputs.os }}
    strategy:
      fail-fast: false
      matrix:
        arg: ${{ fromJSON(inputs.build-args) }}
    steps:
      - name: Checkout TinyUSB
        uses: actions/checkout@v6

      - name: Setup Toolchain
        id: setup-toolchain
        uses: ./.github/actions/setup_toolchain
        with:
          toolchain: ${{ inputs.toolchain }}

      - name: Get Dependencies
        uses: ./.github/actions/get_deps
        with:
          arg: ${{ matrix.arg }}

      - name: Build
        env:
          IAR_LMS_BEARER_TOKEN: ${{ secrets.IAR_LMS_BEARER_TOKEN }}
          TOOLCHAIN: ${{ inputs.toolchain }}
        run: |
          if [ "$TOOLCHAIN" == "esp-idf" ]; then
            docker run --rm -v $PWD:/project -w /project espressif/idf:tinyusb python tools/build.py ${{ matrix.arg }}
          elif [ "${{ inputs.build-system }}" == "cmake-make" ] || [ "${{ inputs.build-system }}" == "make-cmake" ]; then
            python tools/build.py -s make ${{ steps.setup-toolchain.outputs.build_option }} ${{ inputs.build-options }} ${{ matrix.arg }}
            python tools/build.py -s cmake ${{ steps.setup-toolchain.outputs.build_option }} ${{ inputs.build-options }} ${{ matrix.arg }}
          else
            python tools/build.py -s ${{ inputs.build-system }} ${{ steps.setup-toolchain.outputs.build_option }} ${{ inputs.build-options }} ${{ matrix.arg }}
          fi
        shell: bash

      - name: Upload Artifacts for Metrics
        if: ${{ inputs.upload-metrics }}
        uses: actions/upload-artifact@v5
        with:
          name: metrics-${{ matrix.arg }}
          path: cmake-build/cmake-build-*/metrics.json

      - name: Upload Artifacts for Hardware Testing
        if: ${{ inputs.upload-artifacts }}
        uses: actions/upload-artifact@v5
        with:
          name: binaries-${{ matrix.arg }}
          path: |
            cmake-build/cmake-build-*/*/*/*.elf
            cmake-build/cmake-build-*/*/*/*.bin
            cmake-build/cmake-build-*/*/*/*.bin
            cmake-build/cmake-build-*/*/*/bootloader/bootloader.bin
            cmake-build/cmake-build-*/*/*/partition_table/partition-table.bin
            cmake-build/cmake-build-*/*/*/config.env
            cmake-build/cmake-build-*/*/*/flash_args
