name: Semgrep
permissions:
  contents: read
  pull-requests: write

on:
  push:
    branches: [ "master" ]
  pull_request:
    branches: [ "master" ]
  workflow_dispatch:

concurrency:
  group: semgrep-${{ github.ref }}
  cancel-in-progress: true

jobs:
  semgrep:
    name: Semgrep Scan
    runs-on: ubuntu-latest
    if: (github.actor != 'dependabot[bot]')
    steps:
      - name: Checkout code
        uses: actions/checkout@v6

      - name: Run Semgrep
        shell: bash
        run: |
          set +e
          docker run --rm -v "${GITHUB_WORKSPACE}:/src" -w /src \
            semgrep/semgrep:1.161.0 semgrep scan \
            --sarif --output=semgrep.sarif --config=p/default --config=p/kotlin --config=p/owasp-top-ten
          status=$?
          set -e
          if [ "$status" -ne 0 ] && [ "$status" -ne 1 ]; then
            exit "$status"
          fi
          if [ "$status" -eq 1 ] && [ "${{ github.event_name }}" != "pull_request" ]; then
            exit 1
          fi
          exit 0

      - name: Upload SARIF artifact
        if: always()
        uses: actions/upload-artifact@v7
        with:
          name: semgrep-sarif
          path: semgrep.sarif
          if-no-files-found: warn
          retention-days: 7

      - name: Setup reviewdog
        if: always() && github.event_name == 'pull_request'
        uses: reviewdog/action-setup@v1
        with:
          reviewdog_version: v0.20.3

      - name: Report Semgrep results to PR
        if: always() && github.event_name == 'pull_request'
        env:
          REVIEWDOG_GITHUB_API_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          if [ -f semgrep.sarif ]; then
            reviewdog -f=sarif -name="semgrep" -reporter=github-pr-review -level=warning < semgrep.sarif
          fi
