parameters:
- name: CleanArtifactsFolder
  type: boolean
  default: true
- name: CleanBinariesFolder
  type: boolean
  default: true
- name: CleanSourcesFolder
  type: boolean
  default: false
- name: CleanPublishFolder
  type: boolean
  default: false
- name: PublishFolder
  type: string
  default: publish

steps:
- task: PowerShell@2
  displayName: Clean-up Agent Folders
  condition: always()
  env:
    BUILD_ARTIFACTSTAGINGDIRECTORY: $(Build.ArtifactStagingDirectory)
    BUILD_BINARIESDIRECTORY: $(Build.BinariesDirectory)
    BUILD_SOURCESDIRECTORY: $(Build.SourcesDirectory)
    BUILD_PUBLISHDIRECTORY: "$(Agent.BuildDirectory)/${{parameters.PublishFolder}}"
  inputs:
    targetType: inline
    script: |
      if ('${{parameters.CleanArtifactsFolder}}' -eq [bool]::TrueString -and (Test-Path $env:BUILD_ARTIFACTSTAGINGDIRECTORY)) {
          Write-Host -ForegroundColor Cyan "Cleaning folder $env:BUILD_ARTIFACTSTAGINGDIRECTORY"
          Remove-Item -Path "$env:BUILD_ARTIFACTSTAGINGDIRECTORY\*" -Filter '*.*' -Recurse -Force -ErrorAction SilentlyContinue
      }

      if ('${{parameters.CleanBinariesFolder}}' -eq [bool]::TrueString -and (Test-Path $env:BUILD_BINARIESDIRECTORY)) {
          Write-Host -ForegroundColor Cyan "Cleaning folder $env:BUILD_BINARIESDIRECTORY"
          Remove-Item -Path "$env:BUILD_BINARIESDIRECTORY\*" -Filter '*.*' -Recurse -Force -ErrorAction SilentlyContinue
      }

      if ('${{parameters.CleanSourcesFolder}}' -eq [bool]::TrueString -and (Test-Path $env:BUILD_SOURCESDIRECTORY)) {
          Write-Host -ForegroundColor Cyan "Cleaning folder $env:BUILD_SOURCESDIRECTORY"
          Remove-Item -Path "$env:BUILD_SOURCESDIRECTORY\*" -Filter '*.*' -Recurse -Force -ErrorAction SilentlyContinue
      }

      if ('${{parameters.CleanPublishFolder}}' -eq [bool]::TrueString -and (Test-Path $env:BUILD_PUBLISHDIRECTORY)) {
          Write-Host -ForegroundColor Cyan "Cleaning folder $env:BUILD_PUBLISHDIRECTORY"
          Remove-Item -Path "$env:BUILD_PUBLISHDIRECTORY" -Filter '*.*' -Recurse -Force -ErrorAction SilentlyContinue
      }
    pwsh: true
  
