on:
    pull_request:
    push:
        branches:
            - trunk
            - 'release/**'
            - 'wp/**'
    workflow_dispatch:
        inputs:
            version:
                description: ''
                required: true

jobs:
    bump-version:
        name: Bump version
        runs-on: ubuntu-latest
        outputs:
            release_branch: ${{ steps.get_version.outputs.release_branch }}

        steps:
            - name: Compute old and new version
              id: get_version
              run: |
                  OLD_VERSION=$(jq --raw-output '.version' package.json)
                  echo "old_version=${OLD_VERSION}" >> $GITHUB_OUTPUT
                  if [[ ${{ github.event.inputs.version }} == 'stable' ]]; then
                    NEW_VERSION=$(npx semver $OLD_VERSION -i patch)
                  else
                    if [[ $OLD_VERSION == *"rc"* ]]; then
                      NEW_VERSION=$(npx semver $OLD_VERSION -i prerelease)
                    else
                      # WordPress version guidelines: If minor is 9, bump major instead.
                      IFS='.' read -r -a OLD_VERSION_ARRAY <<< "$OLD_VERSION"
                      if [[ ${OLD_VERSION_ARRAY[1]} == "9" ]]; then
                        NEW_VERSION="$(npx semver $OLD_VERSION -i major)-rc.1"
                      else
                        NEW_VERSION="$(npx semver $OLD_VERSION -i minor)-rc.1"
                      fi
                    fi
                  fi
                  echo "new_version=${NEW_VERSION}" >> $GITHUB_OUTPUT
                  IFS='.' read -r -a NEW_VERSION_ARRAY <<< "$NEW_VERSION"
                  RELEASE_BRANCH="release/${NEW_VERSION_ARRAY[0]}.${NEW_VERSION_ARRAY[1]}"
                  echo "release_branch=${RELEASE_BRANCH}" >> $GITHUB_OUTPUT

    build:
        runs-on: ubuntu-latest
        needs: bump-version
        if: |
            always() && (
              github.event_name == 'pull_request' ||
              github.event_name == 'workflow_dispatch' ||
              github.repository == 'test/test'
            )
        steps:
            - name: Checkout code
              uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 # v4.2.1
              with:
                  ref: ${{ needs.bump-version.outputs.release_branch || github.ref }}

            - run: ./bin/build-plugin-zip.sh
