steps:
  - powershell: |
      mkdir .build -ea 0
      "$env:BUILD_SOURCEVERSION" | Out-File -Encoding ascii -NoNewLine .build\commit
      "$env:VSCODE_QUALITY" | Out-File -Encoding ascii -NoNewLine .build\quality
    displayName: Prepare cache flag

  - task: 1ESLighthouseEng.PipelineArtifactCaching.RestoreCacheV1.RestoreCache@1
    inputs:
      keyfile: 'build/.cachesalt, .build/commit, .build/quality'
      targetfolder: '.build, out-build, out-vscode-min, out-vscode-reh-min, out-vscode-reh-web-min'
      vstsFeed: 'BuildCache'
      platformIndependent: true
      alias: 'Compilation'

  - powershell: |
      $ErrorActionPreference = "Stop"
      exit 1
    displayName: Check RestoreCache
    condition: and(succeeded(), ne(variables['CacheRestored-Compilation'], 'true'))

  - task: NodeTool@0
    inputs:
      versionSpec: "12.13.0"

  - task: geeklearningio.gl-vsts-tasks-yarn.yarn-installer-task.YarnInstaller@3
    inputs:
      versionSpec: "1.x"

  - task: UsePythonVersion@0
    inputs:
      versionSpec: '2.x'
      addToPath: true

  - task: AzureKeyVault@1
    displayName: 'Azure Key Vault: Get Secrets'
    inputs:
      azureSubscription: 'ClientToolsInfra_670062 (88d5392f-a34f-4769-b405-f597fc533613)'
      KeyVaultName: ado-secrets
      SecretsFilter: 'github-distro-mixin-password'

  - powershell: |
      . build/azure-pipelines/win32/exec.ps1
      $ErrorActionPreference = "Stop"
      "machine github.com`nlogin azuredatastudio`npassword $(github-distro-mixin-password)" | Out-File "$env:USERPROFILE\_netrc" -Encoding ASCII

      exec { git config user.email "andresse@microsoft.com" }
      exec { git config user.name "AzureDataStudio" }
    displayName: Prepare tooling

  - powershell: |
      git remote add distro "https://github.com/$(VSCODE_MIXIN_REPO).git"
      git fetch distro
      git merge $(node -p "require('./package.json').distro")
    displayName: Merge distro

  - task: 1ESLighthouseEng.PipelineArtifactCaching.RestoreCacheV1.RestoreCache@1
    inputs:
      keyfile: 'build/.cachesalt, .yarnrc, remote/.yarnrc, **/yarn.lock, !**/node_modules/**/yarn.lock, !**/.*/**/yarn.lock, !samples/**/yarn.lock'
      targetfolder: '**/node_modules, !**/node_modules/**/node_modules, !samples/**/node_modules'
      vstsFeed: 'BuildCache'

  - powershell: |
      . build/azure-pipelines/win32/exec.ps1
      $ErrorActionPreference = "Stop"
      $env:CHILD_CONCURRENCY="1"
      exec { yarn --frozen-lockfile }
    displayName: Install dependencies
    env:
      GITHUB_TOKEN: $(github-distro-mixin-password)
    condition: and(succeeded(), ne(variables['CacheRestored'], 'true'))

  - task: 1ESLighthouseEng.PipelineArtifactCaching.SaveCacheV1.SaveCache@1
    inputs:
      keyfile: 'build/.cachesalt, .yarnrc, remote/.yarnrc, **/yarn.lock, !**/node_modules/**/yarn.lock, !**/.*/**/yarn.lock, !samples/**/yarn.lock'
      targetfolder: '**/node_modules, !**/node_modules/**/node_modules, !samples/**/node_modules'
      vstsFeed: 'BuildCache'
    condition: and(succeeded(), ne(variables['CacheRestored'], 'true'))

  - powershell: |
      . build/azure-pipelines/win32/exec.ps1
      $ErrorActionPreference = "Stop"
      exec { yarn postinstall }
    displayName: Run postinstall scripts
    condition: and(succeeded(), eq(variables['CacheRestored'], 'true'))

  - powershell: |
      . build/azure-pipelines/win32/exec.ps1
      $ErrorActionPreference = "Stop"
      exec { node build/azure-pipelines/mixin }
    displayName: Mix in quality

  - powershell: |
      . build/azure-pipelines/win32/exec.ps1
      $ErrorActionPreference = "Stop"
      exec { yarn gulp "package-rebuild-extensions" }
      exec { yarn gulp "vscode-win32-x64-min-ci" }
      # exec { yarn gulp "vscode-reh-win32-x64-min-ci" }
      # exec { yarn gulp "vscode-reh-web-win32-x64-min-ci" }
      exec { yarn gulp "vscode-win32-x64-code-helper" }
      exec { yarn gulp "vscode-win32-x64-inno-updater" }
    displayName: Build
    env:
      VSCODE_MIXIN_PASSWORD: $(github-distro-mixin-password)

  - task: UniversalPackages@0
    displayName: Download SAW Python package
    inputs:
      command: 'download'
      downloadDirectory: '$(agent.builddirectory)\azuredatastudio-win32-x64\resources\app\ads-python'
      feedsToUse: 'internal'
      vstsFeed: '2191dd5f-4aec-491b-ac50-568bbc331c8a'
      vstsFeedPackage: '2e355f03-a97e-499a-949b-f02d62b6160c'
      vstsPackageVersion: '*'
    condition: and(succeeded(), eq(variables['VSCODE_QUALITY'], 'saw'))

  # - powershell: | @anthonydresser unit tests timeout never existing the node process
  #     . build/azure-pipelines/win32/exec.ps1
  #     $ErrorActionPreference = "Stop"
  #     exec { yarn electron x64 }
  #     exec { .\scripts\test.bat --build --coverage --reporter mocha-junit-reporter --tfs "Unit Tests" }
  #   displayName: Run unit tests (Electron)
  #   condition: and(succeeded(), eq(variables['RUN_TESTS'], 'true'))

  - powershell: |
      # Figure out the full absolute path of the product we just built
      # including the remote server and configure the integration tests
      # to run with these builds instead of running out of sources.
      . build/azure-pipelines/win32/exec.ps1
      $ErrorActionPreference = "Stop"
      $AppRoot = "$(agent.builddirectory)\azuredatastudio-win32-x64"
      $AppProductJson = Get-Content -Raw -Path "$AppRoot\resources\app\product.json" | ConvertFrom-Json
      $AppNameShort = $AppProductJson.nameShort
      exec { $env:INTEGRATION_TEST_ELECTRON_PATH = "$AppRoot\$AppNameShort.exe"; $env:VSCODE_REMOTE_SERVER_PATH = "$(agent.builddirectory)\azuredatastudio-reh-win32-x64"; .\scripts\test-integration.bat --build --tfs "Integration Tests" }
    displayName: Run integration tests (Electron)
    condition: and(succeeded(), eq(variables['RUN_TESTS'], 'true'))

  - powershell: |
      . build/azure-pipelines/win32/exec.ps1
      $ErrorActionPreference = "Stop"
      exec { .\scripts\test-unstable.bat --build --tfs }
    continueOnError: true
    condition: and(succeeded(), eq(variables['RUN_UNSTABLE_TESTS'], 'true'))
    displayName: Run unstable tests

  - task: SFP.build-tasks.custom-build-task-1.EsrpCodeSigning@1
    displayName: 'Sign out code'
    inputs:
      ConnectedServiceName: 'Code Signing'
      FolderPath: '$(agent.builddirectory)/azuredatastudio-win32-x64'
      Pattern: '*.exe,*.node,resources/app/node_modules.asar.unpacked/*.dll,swiftshader/*.dll,d3dcompiler_47.dll,libGLESv2.dll,ffmpeg.dll,libEGL.dll,Microsoft.SqlTools.Hosting.dll,Microsoft.SqlTools.ResourceProvider.Core.dll,Microsoft.SqlTools.ResourceProvider.DefaultImpl.dll,MicrosoftSqlToolsCredentials.dll,MicrosoftSqlToolsServiceLayer.dll,Newtonsoft.Json.dll,SqlSerializationService.dll,SqlToolsResourceProviderService.dll,Microsoft.SqlServer.*.dll,Microsoft.Data.Tools.Sql.BatchParser.dll'
      signConfigType: inlineSignParams
      inlineOperation: |
        [
          {
            "keyCode": "CP-230012",
            "operationSetCode": "SigntoolSign",
            "parameters": [
            {
              "parameterName": "OpusName",
              "parameterValue": "Azure Data Studio"
            },
            {
              "parameterName": "OpusInfo",
              "parameterValue": "https://github.com/microsoft/azuredatastudio"
            },
            {
              "parameterName": "PageHash",
              "parameterValue": "/NPH"
            },
            {
              "parameterName": "FileDigest",
              "parameterValue": "/fd sha256"
            },
            {
              "parameterName": "TimeStamp",
              "parameterValue": "/tr \"http://rfc3161.gtm.corp.microsoft.com/TSS/HttpTspServer\" /td sha256"
            }
            ],
            "toolName": "signtool.exe",
            "toolVersion": "6.2.9304.0"
          },
          {
            "keyCode": "CP-230012",
            "operationSetCode": "SigntoolVerify",
            "parameters": [
            {
              "parameterName": "VerifyAll",
              "parameterValue": "/all"
            }
                ],
            "toolName": "signtool.exe",
            "toolVersion": "6.2.9304.0"
          }
        ]
      SessionTimeout: 600
      MaxConcurrency: 5
      MaxRetryAttempts: 20
    condition: and(succeeded(), eq(variables['signed'], true))

  - powershell: |
      . build/azure-pipelines/win32/exec.ps1
      $ErrorActionPreference = "Stop"
      exec { yarn gulp "vscode-win32-x64-user-setup" }
      exec { yarn gulp "vscode-win32-x64-system-setup" }
      exec { yarn gulp "vscode-win32-x64-archive" }
    displayName: Archive & User & System setup

  - task: SFP.build-tasks.custom-build-task-1.EsrpCodeSigning@1
    displayName: 'Sign installers'
    inputs:
      ConnectedServiceName: 'Code Signing'
      FolderPath: '.build'
      Pattern: '*.exe'
      signConfigType: inlineSignParams
      inlineOperation: |
        [
          {
            "keyCode": "CP-230012",
            "operationSetCode": "SigntoolSign",
            "parameters": [
            {
              "parameterName": "OpusName",
              "parameterValue": "Azure Data Studio"
            },
            {
              "parameterName": "OpusInfo",
              "parameterValue": "https://github.com/microsoft/azuredatastudio"
            },
            {
              "parameterName": "PageHash",
              "parameterValue": "/NPH"
            },
            {
              "parameterName": "FileDigest",
              "parameterValue": "/fd sha256"
            },
            {
              "parameterName": "TimeStamp",
              "parameterValue": "/tr \"http://rfc3161.gtm.corp.microsoft.com/TSS/HttpTspServer\" /td sha256"
            }
            ],
            "toolName": "signtool.exe",
            "toolVersion": "6.2.9304.0"
          },
          {
            "keyCode": "CP-230012",
            "operationSetCode": "SigntoolVerify",
            "parameters": [
            {
              "parameterName": "VerifyAll",
              "parameterValue": "/all"
            }
                ],
            "toolName": "signtool.exe",
            "toolVersion": "6.2.9304.0"
          }
        ]
      SessionTimeout: 600
      MaxConcurrency: 5
      MaxRetryAttempts: 20
    condition: and(succeeded(), eq(variables['signed'], true))

  - task: ArchiveFiles@2
    displayName: 'Archive build scripts source'
    inputs:
      rootFolderOrFile: '$(Build.SourcesDirectory)/build'
      archiveType: tar
      archiveFile: '$(Build.BinariesDirectory)/source.tar.gz'

  - task: PublishBuildArtifacts@1
    displayName: 'Publish Artifact: build scripts source'
    inputs:
      PathtoPublish: '$(Build.BinariesDirectory)/source.tar.gz'
      ArtifactName: source

  - powershell: |
      . build/azure-pipelines/win32/exec.ps1
      $ErrorActionPreference = "Stop"
      .\build\azure-pipelines\win32\createDrop.ps1
    displayName: Create Drop

  - task: PublishBuildArtifacts@1
    displayName: 'Publish Artifact: drop'

  - task: PublishTestResults@2
    displayName: 'Publish Test Results test-results.xml'
    inputs:
      testResultsFiles: 'test-results.xml'
      searchFolder: '$(Build.SourcesDirectory)'
      failTaskOnFailedTests: true
    continueOnError: true
    condition: and(succeeded(), eq(variables['RUN_UNSTABLE_TESTS'], 'true'))

  - task: ms.vss-governance-buildtask.governance-build-task-component-detection.ComponentGovernanceComponentDetection@0
    displayName: 'Component Detection'
    inputs:
      failOnAlert: true
