name: Generate Post-Release PR
on:
  workflow_dispatch:

jobs:
  prereqs:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Verify prerequisites
        run: |
          if [[ $GITHUB_REF_NAME != main ]]; then
            echo this workflow should only be run against main
            exit 1
          fi

  create-pull-request-against-main:
    runs-on: ubuntu-latest
    needs:
      - prereqs
    steps:
      - uses: actions/checkout@v4
      - id: setup-java
        name: Set up Java for build
        uses: actions/setup-java@v4
        with:
          distribution: temurin
          java-version: 17

      - name: Set environment variables
        run: |
          version=$(.github/scripts/get-version.sh)
          echo "VERSION=$version" >> $GITHUB_ENV
          prior_version=$(.github/scripts/get-prior-version.sh)
          echo "PRIOR_VERSION=$prior_version" >> $GITHUB_ENV
          if [[ $prior_version =~ ^([0-9]+)\.([0-9]+)\.([0-9]+)$ ]]; then
            major="${BASH_REMATCH[1]}"
            minor="${BASH_REMATCH[2]}"
            patch="${BASH_REMATCH[3]}"
            
            two_releases_ago="$major.$((minor - 1)).$patch"
          else
            echo "unexpected prior version: $prior_version"
            exit 1
          fi
          echo "TWO_VERSIONS_AGO=$two_releases_ago" >> $GITHUB_ENV
      - name: Use CLA approved github bot
        run: .github/scripts/use-cla-approved-github-bot.sh

      - name: Create pull request against main
        env:
          # not using secrets.GITHUB_TOKEN since pull requests from that token do not run workflows
          GH_TOKEN: ${{ secrets.OPENTELEMETRYBOT_GITHUB_TOKEN }}
        run: |
          ./gradlew updateVersionInDocs -Prelease.version=$PRIOR_VERSION
          ./gradlew japicmp -PapiBaseVersion=$TWO_VERSIONS_AGO -PapiNewVersion=$PRIOR_VERSION
          ./gradlew --refresh-dependencies japicmp
   
          message="Post release for version $PRIOR_VERSION"
          body="Post-release updates for version \`$PRIOR_VERSION\`."
          branch="opentelemetrybot/post-release-for-${PRIOR_VERSION}"

          git checkout -b $branch
          git add docs/apidiffs
          git commit -a -m "$message"
          git push --set-upstream origin $branch
          gh pr create --title "$message" \
                       --body "$body" \
                       --base main
