# cSpell:ignore changedfiles
# cSpell:ignore Committish
# cSpell:ignore LASTEXITCODE

steps:
  - template: /eng/common/pipelines/templates/steps/set-default-branch.yml
  - ${{ if eq(variables['Build.Reason'], 'PullRequest') }}:
    - pwsh: |
        # Find the default branch of the repo. The variable value sets in build step.
        Write-Host "Default Branch: $(DefaultBranch)"

        if ((!"$(System.PullRequest.SourceBranch)".StartsWith("sync-eng/common")) -and "$(System.PullRequest.TargetBranch)" -match "^(refs/heads/)?$(DefaultBranch)$")
        {
          $filesInCommonDir  = & "eng/common/scripts/get-changedfiles.ps1" -DiffPath 'eng/common/*'
          if (($LASTEXITCODE -eq 0) -and ($filesInCommonDir.Count -gt 0))
          {
            Write-Host "##vso[task.LogIssue type=error;]Changes to files under 'eng/common' directory should not be made in this Repo`n${filesInCommonDir}"
            Write-Host "##vso[task.LogIssue type=error;]Please follow workflow at https://github.com/Azure/azure-sdk-tools/blob/main/doc/common/common_engsys.md"
            exit 1
          }
        }
        if ((!"$(System.PullRequest.SourceBranch)".StartsWith("sync-.github/workflows")) -and "$(System.PullRequest.TargetBranch)" -match "^(refs/heads/)?$(DefaultBranch)$")
        {
          $filesInCommonDir  = & "eng/common/scripts/get-changedfiles.ps1" -DiffPath '.github/workflows/*'
          if (($LASTEXITCODE -eq 0) -and ($filesInCommonDir.Count -gt 0))
          {
            Write-Host "##vso[task.LogIssue type=error;]Changes to files under '.github/workflows' directory should not be made in this Repo`n${filesInCommonDir}"
            Write-Host "##vso[task.LogIssue type=error;]Please follow workflow at https://github.com/Azure/azure-sdk-tools/blob/main/doc/workflows/engsys_workflows.md"
            exit 1
          }
        }
      displayName: Prevent changes to eng/common and .github/workflows outside of azure-sdk-tools repo
      condition: and(succeeded(), ne(variables['Skip.EngCommonWorkflowEnforcer'], 'true'), not(endsWith(variables['Build.Repository.Name'], '-pr')))