name: Prepare patch release
on:
  workflow_dispatch:

jobs:
  prepare-patch-release:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

      - name: Set environment variables
        run: |
          prior_version=$(grep -Eo "[0-9]+.[0-9]+.[0-9]+" version.gradle.kts | head -1)
          if [[ $prior_version =~ ([0-9]+.[0-9]+).([0-9]+) ]]; then
            major_minor="${BASH_REMATCH[1]}"
            patch="${BASH_REMATCH[2]}"
          else
            echo "unexpected version: $prior_version"
            exit 1
          fi
          echo "VERSION=$major_minor.$((patch + 1))" >> $GITHUB_ENV
          echo "PRIOR_VERSION=$prior_version" >> $GITHUB_ENV

      - name: Bump version
        run: |
          .github/scripts/update-versions.sh "$PRIOR_VERSION" "$PRIOR_VERSION-alpha" "$VERSION" "$VERSION-alpha"

      - name: Bump download link version
        run: |
          sed -Ei "s,https://github.com/open-telemetry/opentelemetry-java-instrumentation/releases/download/v$PRIOR_VERSION/,https://github.com/open-telemetry/opentelemetry-java-instrumentation/releases/download/v$VERSION/," README.md

      - name: Set git user
        run: |
          git config user.name opentelemetry-java-bot
          git config user.email 97938252+opentelemetry-java-bot@users.noreply.github.com

      - name: Create pull request
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          msg="Prepare release $VERSION"
          git commit -a -m "$msg"
          git push origin HEAD:prepare-release-$VERSION
          gh pr create --title "[$GITHUB_REF_NAME] $msg" \
                       --body "$msg" \
                       --head prepare-release-$VERSION \
                       --base $GITHUB_REF_NAME
