name: SonarQube Quality Gate

on:
  push:
    branches:
      - testing
      - main

  pull_request:
    branches:
      - testing
      - main

env:
  SONAR_HOST_URL: ${{ secrets.SONARQUBE_HOST }}
  SONAR_TOKEN: ${{ secrets.SONARQUBE_TOKEN }}

jobs:
  sonarqube:
    name: SonarQube Scan
    runs-on: ubuntu-latest

    container:
      image: sonarsource/sonar-scanner-cli:12.0.0.3214_8.0.1
      options: --user root

    steps:
      - name: Checkout repository
        uses: actions/checkout@v3
        with:
          fetch-depth: 0

      - name: Run SonarQube Scan
        run: |
          REPO_NAME=${{ gitea.event.repository.name }}

          sonar-scanner \
            -Dsonar.projectKey=$REPO_NAME \
            -Dsonar.projectName=$REPO_NAME \
            -Dsonar.sources=. \
            -Dsonar.host.url=$SONAR_HOST_URL \
            -Dsonar.token=$SONAR_TOKEN \
            -Dsonar.exclusions=node_modules/**,dist/**,coverage/** \
            -Dsonar.qualitygate.wait=false

      - name: Install jq (required for parsing)
        if: gitea.event_name == 'pull_request'
        run: |
          apt-get update && apt-get install -y jq

      - name: Get Quality Gate Result
        if: gitea.event_name == 'pull_request'
        run: |
          REPO_NAME=${{ gitea.event.repository.name }}

          curl -s -u $SONAR_TOKEN: \
            "$SONAR_HOST_URL/api/qualitygates/project_status?projectKey=$REPO_NAME" \
            > result.json

          STATUS=$(jq -r '.projectStatus.status' result.json)
          echo "STATUS=$STATUS" >> $GITHUB_ENV

      - name: Comment on PR
        if: gitea.event_name == 'pull_request'
        run: |
          if [ "$STATUS" = "OK" ]; then
            MESSAGE=" SonarQube Quality Gate PASSED"
          else
            MESSAGE=" SonarQube Quality Gate FAILED"
          fi

          curl -X POST \
            -H "Authorization: token ${{ secrets.GITEA_TOKEN }}" \
            -H "Content-Type: application/json" \
            -d "{\"body\": \"$MESSAGE\"}" \
            ${{ gitea.api_url }}/repos/${{ gitea.repository }}/issues/${{ gitea.event.pull_request.number }}/comments