name: Preview Pull Request

#! Safety:
#! this workflow should not execute any untrusted input at all
#! see the docs on `pull_request_target` for more
on:
    pull_request_target:
        types: [synchronize, reopened, labeled]

jobs:
    preview:
        runs-on: ubuntu-latest
        # make sure the pull request is labeled with 'use-preview'
        if: github.event.label.name == 'use-preview' || contains(github.event.pull_request.labels.*.name, 'use-preview')
        env:
            BASE: refs/pull/${{ github.event.pull_request.number }}/merge
            REPO: ${{ github.event.repository.name }}

        steps:
            - uses: actions/checkout@v2

            - uses: actions/checkout@v2
              with:
                  # Head commit of the pull request
                  ref: ${{ github.event.pull_request.head.sha }}
                  path: pull
                  submodules: recursive

            - name: build
              uses: ./.github/actions/build
              with:
                  base: /${{ env.REPO }}/${{ env.BASE }}/
                  folder: pull

            - name: publish preview
              uses: JamesIves/github-pages-deploy-action@4.1.5
              with:
                  folder: pull/dist
                  branch: build-previews
                  target-folder: ${{ env.BASE }}
                  single-commit: true
                  commit-message: "Publishing build result from #${{ github.event.pull_request.number }}"

            - name: send comment
              uses: marocchino/sticky-pull-request-comment@v2
              with:
                  header: Preview environment
                  message: |
                      ## Preview environment
                      https://${{ github.repository_owner }}.github.io/${{ env.REPO }}/${{ env.BASE }}/

                      This link will remain active until the `use-preview` label is removed.
