name: Sonar Code Coverage Upload
on:
  workflow_run:
    workflows: ["Build/Test"]
    types: [completed]
jobs:
  sonar:
    name: Sonar
    runs-on: ubuntu-latest
    if: github.event.workflow_run.conclusion == 'success'
    steps:
      - uses: actions/checkout@v4
        with:
          repository: ${{ github.event.workflow_run.head_repository.full_name }}
          ref: ${{ github.event.workflow_run.head_branch }}
          fetch-depth: 0
      - name: 'Download code coverage'
        uses: actions/github-script@v7
        with:
          script: |
            let allArtifacts = await github.rest.actions.listWorkflowRunArtifacts({
               owner: context.repo.owner,
               repo: context.repo.repo,
               run_id: context.payload.workflow_run.id,
            });
            let matchArtifact = allArtifacts.data.artifacts.filter((artifact) => {
              return artifact.name == "oc-code-coverage"
            })[0];
            let download = await github.rest.actions.downloadArtifact({
               owner: context.repo.owner,
               repo: context.repo.repo,
               artifact_id: matchArtifact.id,
               archive_format: 'zip',
            });
            let fs = require('fs');
            fs.writeFileSync(`${process.env.GITHUB_WORKSPACE}/oc-code-coverage.zip`, Buffer.from(download.data));
      - name: 'Unzip code coverage'
        run: unzip oc-code-coverage.zip -d coverage
      - name: set env vars 
        run: | 
          echo "SONAR_PR_NUM=$(cat coverage/pr_num.txt)" >> $GITHUB_ENV
          echo "SONAR_BASE=$(cat coverage/base.txt)" >> $GITHUB_ENV
          echo "SONAR_HEAD=$(cat coverage/head.txt)" >> $GITHUB_ENV
      # on develop branch, only run a baseline scan
      - name: SonarCloud Scan (Baseline)
        uses: sonarsource/sonarcloud-github-action@master
        if: env.SONAR_HEAD == 'develop'
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
        with:
          args: >
            -Dsonar.scm.revision=${{ github.event.workflow_run.head_sha }}
            -Dsonar.projectKey=opencost_opencost
            -Dsonar.organization=opencost
            -Dsonar.branch.name=develop
            -Dsonar.branch.target=develop
      - name: SonarCloud Scan (PR)
        uses: sonarsource/sonarcloud-github-action@master
        if: env.SONAR_HEAD != 'develop'
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
        with:
          args: >
            -Dsonar.scm.revision=${{ github.event.workflow_run.head_sha }}
            -Dsonar.pullrequest.key=${{ env.SONAR_PR_NUM }}
            -Dsonar.pullrequest.branch=${{ env.SONAR_HEAD }}
            -Dsonar.pullrequest.base=${{ env.SONAR_BASE }}
            -Dsonar.projectKey=opencost_opencost
            -Dsonar.organization=opencost
