# cSpell:ignore changedfiles
# cSpell:ignore credscan
# cSpell:ignore securedevelopmentteam
# cSpell:ignore postanalysis
parameters:
  SuppressionFilePath: 'eng/CredScanSuppression.json'
  BaselineFilePath: ''
  SourceDirectory: $(Build.SourcesDirectory)
  ServiceDirectory: ''

steps:
- pwsh: |
    if ("$(Build.Reason)" -eq 'PullRequest') {
      $changedFiles = & "eng/common/scripts/get-changedfiles.ps1"
      $changedFiles | ForEach-Object { Add-Content -Path "${{ parameters.SourceDirectory }}/credscan.tsv" -Value "${{ parameters.SourceDirectory }}/$_"}
    }
    else {
      $scanFolder = ""
      if ("${{ parameters.ServiceDirectory }}" -ne '') {
        $scanFolder = "sdk/${{ parameters.ServiceDirectory }}"
      }
      Set-Content "${{ parameters.SourceDirectory }}/credscan.tsv" -Value "${{ parameters.SourceDirectory }}/$scanFolder"
    }
    if(Test-Path "${{ parameters.SourceDirectory }}/credscan.tsv") {
      Get-Content "${{ parameters.SourceDirectory }}/credscan.tsv"
    }
    else {
      Write-Host "##vso[task.setvariable variable=SKIP_CREDSCAN]true"
    }
  displayName: CredScan setup
  condition: succeededOrFailed()

- task: securedevelopmentteam.vss-secure-development-tools.build-task-credscan.CredScan@3
  displayName: CredScan running
  condition: and(succeededOrFailed(), ne(variables['SKIP_CREDSCAN'], true))
  inputs:
    toolVersion: 2.3.12.23
    scanFolder: "${{ parameters.SourceDirectory }}/credscan.tsv"
    suppressionsFile: ${{ parameters.SuppressionFilePath }}
- task: securedevelopmentteam.vss-secure-development-tools.build-task-postanalysis.PostAnalysis@2
  displayName: CredScan result analysis
  condition: and(succeededOrFailed(), ne(variables['SKIP_CREDSCAN'], true))
  inputs:
    GdnBreakBaselineFiles: ${{ parameters.BaselineFilePath }}
    GdnBreakAllTools: false
    GdnBreakGdnToolCredScan: true
    GdnBreakGdnToolCredScanSeverity: Error
    GdnBreakBaselines: baseline
    # Used for generating baseline file.
    # GdnBreakOutputBaselineFile: baseline
    # GdnBreakOutputBaseline: baseline
- pwsh: |
    Write-Host "Please check https://aka.ms/azsdk/credscan for more information about the cred scan failure."
  displayName: CredScan troubleshooting guide
  condition: and(failed(), ne(variables['SKIP_CREDSCAN'], true))
