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: |
          version=$(.github/scripts/get-version.sh)
          if [[ $version =~ ([0-9]+\.[0-9]+)\.([0-9]+) ]]; then
            major_minor="${BASH_REMATCH[1]}"
            patch="${BASH_REMATCH[2]}"
          else
            echo "unexpected version: $version"
            exit 1
          fi
          echo "VERSION=$major_minor.$((patch + 1))" >> $GITHUB_ENV

      - name: Check change log has been updated
        run: |
          if ! grep --quiet "^## Version $VERSION" CHANGELOG.md; then
            echo the change log needs to be updated
            exit 1
          fi

      - name: Update version
        run: .github/scripts/update-version.sh $VERSION

      - name: Set git user
        run: .github/scripts/set-git-user.sh

      - name: Create pull request
        env:
          # not using the default GITHUB_TOKEN because pull requests generated by it do not run any workflows
          GITHUB_TOKEN: ${{ secrets.BOT_TOKEN }}
        run: |
          message="Prepare release $VERSION"
          branch="prepare-release-${VERSION}"

          git commit -a -m "$message"
          git push origin HEAD:$branch
          gh pr create --title "[$GITHUB_REF_NAME] $message" \
                       --body "$message." \
                       --head $branch \
                       --base $GITHUB_REF_NAME
