name: Prepare release branch
on:
  workflow_dispatch:

jobs:
  create-pull-request-against-release-branch:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

      - name: Create release branch
        id: create-release-branch
        run: |
          version=$(grep -Eo "[0-9]+.[0-9]+.0-SNAPSHOT" version.gradle.kts | sed 's/-SNAPSHOT//')
          release_branch_name=$(echo $version | sed -E 's,([0-9]+)\.([0-9]+)\.0,release/v\1.\2.x,')

          git push origin HEAD:$release_branch_name

          echo "VERSION=$version" >> $GITHUB_ENV
          echo "RELEASE_BRANCH_NAME=$release_branch_name" >> $GITHUB_ENV

      - name: Drop snapshot from version
        run: |
          sed -ri "s/val snapshot = true/val snapshot = false/" version.gradle.kts

      - 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 against the release branch
        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 "[$RELEASE_BRANCH_NAME] $msg" \
                       --body "$msg" \
                       --head prepare-release-$VERSION \
                       --base $RELEASE_BRANCH_NAME

  create-pull-request-against-main:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

      - name: Bump snapshot version
        run: |
          version=$(grep -Eo "[0-9]+.[0-9]+.0-SNAPSHOT" version.gradle.kts | sed 's/-SNAPSHOT//')
          if [[ $version =~ ([0-9]+).([0-9]+).0 ]]; then
            major="${BASH_REMATCH[1]}"
            minor="${BASH_REMATCH[2]}"
          else
            echo "unexpected version: $version"
            exit 1
          fi
          next_version="$major.$((minor + 1)).0"
          sed -ri "s/$version-SNAPSHOT/$next_version-SNAPSHOT/" version.gradle.kts

      - 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 against main
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          msg="Bump version"
          git commit -a -m "$msg"
          git push origin HEAD:bump-snapshot-version
          gh pr create --title "$msg" \
                       --body "$msg" \
                       --head bump-snapshot-version \
                       --base main
