name: Build

on:
  push:
    branches:
      - main
  pull_request:
  workflow_dispatch:

jobs:
  build:
    name: OS=${{ matrix.os }}, Gradle=${{ matrix.gradle }}
    strategy:
      matrix:
        os: [ ubuntu-24.04-arm, windows-latest ]
        # Test on the minimum Gradle version and the latest.
        gradle: [ 9.4.0, current ]
    runs-on: ${{ matrix.os }}
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-java@v5
        with:
          distribution: 'zulu'
          java-version-file: .github/workflows/.java-version
      - uses: gradle/actions/setup-gradle@v6
      - run: ./gradlew build "-PtestGradleVersion=${{ matrix.gradle }}" --stacktrace --non-interactive

  # Status check that is required in branch protection rules.
  build-status:
    needs:
      - build
    runs-on: ubuntu-slim
    if: always()
    steps:
      - name: Check
        run: |
          results=$(tr -d '\n' <<< '${{ toJSON(needs.*.result) }}')
          if ! grep -q -v -E '(failure|cancelled)' <<< "$results"; then
            echo "One or more required jobs failed"
            exit 1
          fi
          echo "All required jobs completed successfully."

  publish-snapshot:
    needs: build-status
    runs-on: ubuntu-24.04-arm
    if: github.event.repository.fork == false && github.ref == 'refs/heads/main'
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-java@v5
        with:
          distribution: 'zulu'
          java-version-file: .github/workflows/.java-version
      - uses: gradle/actions/setup-gradle@v6
        with:
          cache-read-only: true
          dependency-graph: 'generate-submit-and-upload'
      - run: ./gradlew publishToMavenCentral
        env:
          ORG_GRADLE_PROJECT_mavenCentralUsername: ${{ secrets.CENTRAL_PORTAL_USERNAME }}
          ORG_GRADLE_PROJECT_mavenCentralPassword: ${{ secrets.CENTRAL_PORTAL_PASSWORD }}
          ORG_GRADLE_PROJECT_signingInMemoryKey: ${{ secrets.GPG_KEY }}
          ORG_GRADLE_PROJECT_signingInMemoryKeyPassword: ${{ secrets.GPG_KEY_PASSWORD }}
