name: Pull Request Build

on:
  pull_request:

permissions:
  contents: write
  pull-requests: write

jobs:
  build:
    name: Build
    runs-on: ubuntu-latest
    steps:
      - name: Checkout sources
        uses: actions/checkout@v6
      - name: Setup Java 8
        uses: actions/setup-java@v5
        with:
          distribution: 'temurin'
          java-version: 8
      - name: Setup Java 11
        uses: actions/setup-java@v5
        with:
          distribution: 'temurin'
          java-version: 11
      - name: Setup Java 17
        uses: actions/setup-java@v5
        with:
          distribution: 'temurin'
          java-version: 17
      - name: Setup Java
        uses: actions/setup-java@v5
        with:
          distribution: 'temurin'
          java-version: 21
      - name: Setup Gradle
        uses: gradle/actions/setup-gradle@v6
      - name: Setup Maven Repository
        env:
          SW_MAVEN_CREDENTIALS: ${{ secrets.SW_MAVEN_CREDENTIALS }}
        run: |
          echo "$SW_MAVEN_CREDENTIALS" > steamwar.properties
      - name: Build with Gradle
        run: ./gradlew build --no-daemon

      - name: Merge successful backport PR
        shell: bash
        env:
          GITHUB_TOKEN: ${{ secrets.CI_BOT_TOKEN }}
          BACKPORT_BRANCH_PREFIX: backport/commoncore
        run: |
          set -euo pipefail

          head_branch="$(jq -r '.pull_request.head.ref // ""' "$GITHUB_EVENT_PATH")"
          base_branch="$(jq -r '.pull_request.base.ref // ""' "$GITHUB_EVENT_PATH")"
          pr_number="$(jq -r '.pull_request.number' "$GITHUB_EVENT_PATH")"

          if [[ "${head_branch}" != "${BACKPORT_BRANCH_PREFIX}/"* ]]; then
            echo "Not a CommonCore backport PR."
            exit 0
          fi

          if [[ "${base_branch}" != version/* ]]; then
            echo "Backport PR target is not a version/* branch."
            exit 0
          fi

          api_url="${GITHUB_API_URL:-${GITHUB_SERVER_URL}/api/v1}"

          curl -fsS -X POST \
            -H "Accept: application/json" \
            -H "Authorization: token ${GITHUB_TOKEN}" \
            -H "Content-Type: application/json" \
            -d '{"Do":"merge","delete_branch_after_merge":true}' \
            "${api_url}/repos/${GITHUB_REPOSITORY}/pulls/${pr_number}/merge"
