name: Backport
on:
  pull_request:
    types: [ closed ]
jobs:
  backport:
    runs-on: ubuntu-20.04
    if: github.event.pull_request.merged == true && contains(github.event.pull_request.body, 'Need to cherry-pick to the release branch')
    name: Backport
    steps:
      - name: Create Reminder for cherry-pick and assign it to pr author
        env:
          TITLE: ${{ github.event.pull_request.title }}
        run: |
          HTTP_RESPONSE=`curl -v -X "POST" "https://api.github.com/repos/${{ github.repository }}/issues" \
              -H "Authorization: token ${{ secrets.REPO_ACCESS_TOKEN }}" \
              -H "Content-Type: text/plain; charset=utf-8" \
              --write-out "%{http_code}\n"\
              -o /dev/null\
              -d '{
            "title": "Backport #${{ github.event.number }} '"$TITLE"'",
            "body": "#${{ github.event.number }}",
            "assignees": [
              "${{ github.event.pull_request.user.login }}"
            ],
            "labels": [
              "s:backport-needed"
            ]
          }'`

          if [[ $HTTP_RESPONSE == '422' ]];then
              echo "create issue without assignees"
              curl -v -X "POST" "https://api.github.com/repos/${{ github.repository }}/issues" \
                -H "Authorization: token ${{ secrets.REPO_ACCESS_TOKEN }}" \
                -H "Content-Type: text/plain; charset=utf-8" \
                --write-out "%{http_code}\n"\
                -o /dev/null\
                -d '{
                "title": "Backport #${{ github.event.number }} '"$TITLE"'",
                "body": "#${{ github.event.number }}",
                "labels": [
                  "s:backport-needed"
                ]
              }'
          fi

