name: Link Checker (PR Build)

on:
  # Note: DO NOT change this to "pull request_target" since that grants
  # permission for PRs from random forks to modify the repo itself!
  pull_request:
    types: [opened, edited, synchronize]

jobs:
  build:
    name: "Build and Check Links"
    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v2

    - name: Set up Python ${{ matrix.python-version }}
      uses: actions/setup-python@v2
      with:
        python-version: "3.9"

    - name: Install dependencies
      run: |
        python -m pip install --upgrade pip
        pip install dactyl lxml

    - name: Check for Conflict Markers
      run: |
        tool/conflictmarkers.sh

    - name: Build docs
      run: |
        echo '{"github_forkurl": "https://github.com/${{ github.event.pull_request.head.repo.full_name }}", "github_branch": "${{ github.head_ref }}", "github_pr_id": "${{ github.event.number }}", "is_pr_build": true}' > dactyl_vars.json
        tool/build_all_langs.sh --vars dactyl_vars.json

    - name: Run Dactyl Link Checker
      continue-on-error: true
      id: linkcheck
      run: |
        dactyl_link_checker -o -q > linkreport.txt

    - name: Assemble Link Report
      run: |
        sed -i '1,/---------------------------------------/d' linkreport.txt
        echo 'LINKREPORT<<EOF' >> $GITHUB_ENV
        cat linkreport.txt >> $GITHUB_ENV
        echo 'EOF' >> $GITHUB_ENV
        cat linkreport.txt

    - name: Run Style Checker
      continue-on-error: true
      run: dactyl_style_checker -q > out/style_report.txt

    # This only works with PRs that are in-repo, not from forks.
    # TODO: delete folders from gh-pages when PRs are closed
    - name: Deploy to gh-pages
      if: ${{ !github.event.pull_request.head.repo.fork }}
      uses: peaceiris/actions-gh-pages@v3
      with:
        github_token: ${{ secrets.GITHUB_TOKEN }}
        publish_dir: ./out
        destination_dir: ./pr-preview/${{ github.head_ref }}

    - name: Summarize Output
      if: ${{ !github.event.pull_request.head.repo.fork }}
      uses: thollander/actions-comment-pull-request@v1
      with:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        message: "${{ env.LINKREPORT }}\n\nPreview: https://${{ github.repository_owner }}.github.io/${{ github.event.pull_request.base.repo.name }}/pr-preview/${{ github.head_ref }}/\n\n[Style Report](https://${{ github.repository_owner }}.github.io/${{ github.event.pull_request.base.repo.name }}/pr-preview/${{ github.head_ref }}/style_report.txt)"

      # Workaround for https://github.com/actions/toolkit/issues/399
      # to mark the CI as failed if the link checker found broken links.
    - name: Mark Failure
      if: steps.linkcheck.outcome != steps.linkcheck.conclusion
      run: exit 1
