name: PR build check

on:
  pull_request:
    paths:
      - '**'
      - '!**.md'
      - '!.github/**'
      - '.github/workflows/build_pull_request.yml'

concurrency:
  group: ${{ github.workflow }}-${{ github.event.pull_request.number }}
  cancel-in-progress: true

env:
  CI_CHUNK_SIZE: 65

jobs:
  prepare:
    name: Prepare job
    runs-on: docker
    outputs:
      individualMatrix: ${{ steps.generate-matrices.outputs.individualMatrix }}
    steps:
      - name: Clone repo
        uses: https://github.com/actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4

      - name: Get number of modules
        run: |
          set -x
          projects=(src/*/*)

          echo "NUM_INDIVIDUAL_MODULES=${#projects[@]}" >> $GITHUB_ENV

      - id: generate-matrices
        name: Create output matrices
        uses: https://github.com/actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7
        with:
          script: |
            const numIndividualModules = process.env.NUM_INDIVIDUAL_MODULES;
            const chunkSize = process.env.CI_CHUNK_SIZE;

            const numIndividualChunks = Math.ceil(numIndividualModules / chunkSize);

            console.log(`Individual modules: ${numIndividualModules} (${numIndividualChunks} chunks of ${chunkSize})`);

            core.setOutput('individualMatrix', { 'chunk': [...Array(numIndividualChunks).keys()] });

  build_individual:
    name: Build individual modules
    needs: prepare
    runs-on: docker
    strategy:
      matrix: ${{ fromJSON(needs.prepare.outputs.individualMatrix) }}
    steps:
      - name: Checkout PR
        uses: https://github.com/actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4

      - name: Set up JDK
        uses: https://github.com/actions/setup-java@387ac29b308b003ca37ba93a6cab5eb57c8f5f93 # v4
        with:
          java-version: 17
          distribution: temurin

      - name: Set up Gradle
        uses: https://github.com/gradle/actions/setup-gradle@417ae3ccd767c252f5661f1ace9f835f9654f2b5 # v3
        with:
          cache-read-only: true

      - name: Build extensions (chunk ${{ matrix.chunk }})
        env:
          CI_CHUNK_NUM: ${{ matrix.chunk }}
        run: chmod +x ./gradlew && ./gradlew -p src assembleDebug