name: Draft New Release

on:
  workflow_dispatch:

jobs:
  draft_new_release:
    name: Draft a new release
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v2
        with:
          fetch-depth: 0 # avoid shallow clone for NBGV
          token: ${{ secrets.GITHUB_TOKEN }} # Allows git push

      - name: Set up NBGV
        uses: dotnet/nbgv@master
        id: nbgv

      - run: echo "VERSION=${{ steps.nbgv.outputs.SimpleVersion }}${{ steps.nbgv.outputs.PrereleaseVersion }}" >> $GITHUB_ENV

      - name: Initialize mandatory git config
        run: |
          git config user.name "GitHub Actions"
          git config user.email noreply@github.com

      # TODO: Support specifying a SHA1 to branch from in the workflow run?
      - name: Create Release Branch
        run: |
          nbgv prepare-release
          git checkout release/${{ steps.nbgv.outputs.SimpleVersion }}

      - name: Update changelog
        uses: thomaseizinger/keep-a-changelog-new-release@1.1.0
        with:
          version: ${{ env.VERSION }}

      - name: Commit Changelog
        run: git commit -m 'Finalize changelog for version ${{ env.VERSION }}' -- CHANGELOG.md

      - name: Push master and release branch
        run: git push origin master +release/${{ steps.nbgv.outputs.SimpleVersion }}

      - name: Create Pull Request
        uses: peter-evans/create-pull-request@v3
        id: cpr
        with:
          token: ${{ secrets.GITHUB_TOKEN }}
          delete-branch: true
          base: master

      - name: Enable Pull Request Automerge
        uses: peter-evans/enable-pull-request-automerge@v1
        with:
          token: ${{ secrets.GITHUB_TOKEN }}
          pull-request-number: ${{ steps.cpr.outputs.pull-request-number }}
          merge-method: merge
          title: "Preparation for Release: ${{ env.VERSION }}"
          body: |
            This pull request represents changes to be made in preparation of the next release,
            ${{ env.VERSION }}.

            Once the build and release tasks in this PR are completed, the release will be created
            and this PR will be automatically merged.

      - name: Auto Approve Pull Request
        uses: actions/github-script@v3
        if: steps.cpr.outputs.pull-request-operation == 'created'
        with:
          github-token: ${{ secrets.GITHUB_TOKEN }}
          script: |
            await github.pulls.createReview({
              owner: context.repo.owner,
              repo: context.repo.repo,
              pull_number: ${{ steps.cpr.outputs.pull-request-number }},
              event: 'APPROVE'
            })