---
name: 🕴️ Style check

on:
  push:
    branches:
      - master
      - release-**
  pull_request:
    branches:
      - master
      - release-**
  issue_comment:
    types: [created]

jobs:
  astyle-check:
    runs-on: ubuntu-20.04
    steps:
      - uses: actions/github-script@v5
        if: ${{ github.event.issue.pull_request }}
        id: get-pr
        with:
          script: |
            const request = {
              owner: context.repo.owner,
              repo: context.repo.repo,
              pull_number: context.issue.number
            }
            core.info(`Getting PR #${request.pull_number} from ${request.owner}/${request.repo}`)
            try {
              const result = await github.rest.pulls.get(request)
              return result.data
            } catch (err) {
              core.setFailed(`Request failed with error ${err}`)
            }

      - uses: actions/checkout@v2
        if: ${{ github.event.issue.pull_request }}
        with:
          repository: ${{ fromJSON(steps.get-pr.outputs.result).head.repo.full_name }}
          ref: ${{ fromJSON(steps.get-pr.outputs.result).head.sha }} # or .head.ref for branch name

      - uses: actions/checkout@v2
        if: ${{ !github.event.issue.pull_request }}

      - uses: khan/pull-request-comment-trigger@master
        id: indent-check
        if: ${{ github.event.issue.pull_request }}
        with:
          trigger: '@qfield-fairy style please'
          reaction: rocket
        env:
          GITHUB_TOKEN: '${{ secrets.FAIRY_TOKEN }}'

      - name: Check astyle
        id: astyle-check
        run: |
          sudo apt install -y astyle
          find src/ -name '*.cpp' -o -name '*.h' | xargs ./scripts/astyle.sh
          find test/ -name '*.cpp' -o -name '*.h' | xargs ./scripts/astyle.sh
          if [ ! -z "$(git status --porcelain)" ]; then
            echo "::error::Indentation errors found (astyle)"
            echo "::group::Indentation changes"
            git diff
            echo "::endgroup"
            echo '::set-output name=changed::true'
          fi

      - name: Comment
        uses: thollander/actions-comment-pull-request@main
        if: steps.indent-check.outputs.changed == 'true' && steps.indent-check.outputs.triggered != 'true'
        with:
          message: |
            Code formatting issues have been detected.

            Reply with `@qfield-fairy style please` to fix it up 🪄.
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - uses: EndBug/add-and-commit@v7.4.0
        if: steps.indent-check.outputs.triggered == 'true'
        with:
          author_name: Style Fairy
          author_email: fairy@qfield.org
          message: 'Committing astyle changes'
          branch: ${{ fromJSON(steps.get-pr.outputs.result).head.ref }}
        env:
          GITHUB_TOKEN: ${{ secrets.FAIRY_TOKEN }}
