name: Backport
on:
  workflow_dispatch:
    inputs:
      number:
        description: "The pull request # to backport"
        required: true

jobs:
  backport:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
        with:
          # history is needed to run git cherry-pick below
          fetch-depth: 0

      - 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:
          NUMBER: ${{ github.event.inputs.number }}
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          commit=$(gh pr view $NUMBER --json mergeCommit --jq .mergeCommit.oid)
          title=$(gh pr view $NUMBER --json title --jq .title)
          url=$(gh pr view $NUMBER --json url --jq .url)

          git cherry-pick $commit
          git push origin HEAD:backport-$NUMBER-to-$GITHUB_REF_NAME

          gh pr create --title "[$GITHUB_REF_NAME] $title" \
                       --body "Clean cherry-pick of #$NUMBER to the $GITHUB_REF_NAME branch." \
                       --head backport-$NUMBER-to-$GITHUB_REF_NAME \
                       --base $GITHUB_REF_NAME
