name: Check Precompiled Binaries

on:
  pull_request:
    paths:
      - 'enc_bootloader/**'
      - 'picoboot_flash_id/**'
      - 'xip_ram_perms/**'

jobs:
  check-precompiled:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Install dependencies (Linux)
        run: sudo apt install cmake ninja-build python3 build-essential gcc-arm-none-eabi libnewlib-arm-none-eabi libstdc++-arm-none-eabi-newlib libusb-1.0-0-dev

      - name: Checkout Pico SDK
        uses: actions/checkout@v4
        with:
          repository: raspberrypi/pico-sdk
          ref: develop
          path: pico-sdk
          submodules: 'true'

      - name: Build and Install
        run: |
          cmake -S . -B build -G "Ninja" -D PICO_SDK_PATH="${{ github.workspace }}/pico-sdk" -D USE_PRECOMPILED=FALSE
          cmake --build build
          sudo cmake --install build

      - name: Check precompiled binaries have been updated
        run: |
          updated_files=$(curl -s -u "${{ github.repository_owner }}":"${{ github.token }}" -H "Accept: application/vnd.github.v3+json" "${{ github.event.pull_request._links.self.href }}/files")
          updated_files=$(jq -r '.[] | .filename' <<<"$updated_files")

          export updated_files
          echo "Updated files: $updated_files"
          ./.github/workflows/check_precompiled.sh

      - name: Upload new precompiled binaries
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: precompiled-binaries
          path: |
            enc_bootloader/enc_bootloader.elf
            enc_bootloader/enc_bootloader_mbedtls.elf
            picoboot_flash_id/flash_id.bin
            xip_ram_perms/xip_ram_perms.elf
