on:
  create:
    branches:

name: Open Release PR for review

jobs:
  # This job is necessary because GitHub does not (yet) support
  # filtering `create` triggers by branch name.
  # See: https://github.community/t/trigger-job-on-branch-created/16878/5
  should_create_pr:
    name: Check if PR for branch already exists
    runs-on: ubuntu-latest
    outputs:
      result: ${{ steps.is_release_branch_without_pr.outputs.result }}
    steps:
      - id: is_release_branch_without_pr
        name: Find matching PR
        uses: actions/github-script@v3
        with:
          github-token: ${{ secrets.GITHUB_TOKEN }}
          script: |
            // Search for an existing PR with head & base
            //  that match the created branch

            const [releaseBranchName] = context.ref.match("release/v[0-9]+\.[0-9]+\.[0-9]+") || []

            if(!releaseBranchName) { return false }

            const {data: prs} = await github.pulls.list({
                ...context.repo,
                state: 'open',
                head: `1Password:${releaseBranchName}`,
                base: context.payload.master_branch
            })

            return prs.length === 0

  create_pr:
    needs: should_create_pr
    if: needs.should_create_pr.outputs.result == 'true'
    name: Create Release Pull Request
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2

      - name: Parse release version
        id: get_version
        run: echo "::set-output name=version::$(echo $GITHUB_REF | sed 's|^refs/heads/release/v?*||g')"

      - name: Prepare Pull Request
        id: prep_pr
        run: |
          CHANGELOG_PATH=$(printf "%s/CHANGELOG.md" "${GITHUB_WORKSPACE}")

          LOG_ENTRY=$(awk '/START\/v[0-9]+\.[0-9]+\.[0-9]+*/{f=1; next} /---/{if (f == 1) exit} f' "${CHANGELOG_PATH}")
          export PR_BODY=$(cat <<EOF
          This is an automated PR for a new release.

          Please check the following before approving:
          - [ ] Changelog is accurate. The documented changes for this release are printed below.
          - [ ] Any files referencing a version number. Confirm it matches the version number in the branch name.
          ---
          ## Release Changelog Preview
          ${LOG_ENTRY}
          EOF
          )

          # Sanitizes multiline strings for action outputs (https://medium.com/agorapulse-stories/23f56447d209)
          PR_BODY="${PR_BODY//'%'/'%25'}"
          PR_BODY="${PR_BODY//$'\n'/'%0A'}"
          PR_BODY="${PR_BODY//$'\r'/'%0D'}"
          echo "::set-output name=pr_body::$(echo "$PR_BODY")"

      - name: Create Pull Request via API
        id: post_pr
        uses: octokit/request-action@v2.x
        with:
          route: POST /repos/${{ github.repository }}/pulls
          title: ${{ format('Prepare Release - v{0}', steps.get_version.outputs.version) }}
          head: ${{ github.ref }}
          base: ${{ github.event.master_branch }}
          body: ${{ toJson(steps.prep_pr.outputs.pr_body) }}
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
