resources:
  repositories:
    - repository: azure-sdk-build-tools
      type: git
      name: internal/azure-sdk-build-tools
      ref: refs/tags/azure-sdk-build-tools_20230613.1

parameters:
- name: Artifacts
  type: object
  default: []
- name: AdditionalModules
  type: object
  default: []
- name: ServiceDirectory
  type: string
  default: not-specified
- name: SDKType
  type: string
  default: not-specified
- name: TargetDocRepoName
  type: string
  default: azure-docs-sdk-java
- name: EnableBatchRelease
  type: boolean
  default: false
- name: UseEsrpRelease
  type: boolean
  default: true
- name: MatrixFilters
  type: object
  default: []
- name: LanguageFilter
  type: object
  default: []

variables:
  - template: /eng/pipelines/templates/variables/globals.yml

stages:
  - stage: Build
    jobs:
    - template: /eng/pipelines/templates/jobs/ci.yml
      parameters:
        ServiceDirectory: ${{parameters.ServiceDirectory}}
        Artifacts: ${{ parameters.Artifacts }}
        ReleaseArtifacts:
        - ${{ if and(eq(variables['System.TeamProject'], 'internal'), eq(variables['Build.Reason'], 'Manual')) }}:
          - ${{ each artifact in parameters.Artifacts }}:
            - ${{ if ne(artifact.releaseInBatch, 'false') }}:
              - ${{ artifact }}
        - ${{ else }}:
          - ${{ parameters.Artifacts }}
        AdditionalModules: ${{ parameters.AdditionalModules }}
        SDKType: ${{parameters.SDKType}}
        MatrixConfigs:
          - Name: Cosmos_ci_test
            Path: eng/pipelines/templates/stages/platform-matrix.json
            Selection: sparse
            NonSparseParameters: Agent
            GenerateVMJobs: true
        MatrixFilters:
          - TestFromSource=^$|false
          - ${{ parameters.MatrixFilters }}
        MatrixReplace:
          - AZURE_TEST.*=.*/
        BuildParallelization: 1
        TestOptions: '-Punit'

  - stage: TestEmulator
    displayName: Test Emulator
    dependsOn: []
    jobs:
    - template: /eng/common/pipelines/templates/jobs/archetype-sdk-tests-generate.yml
      parameters:
        JobTemplatePath: /eng/pipelines/templates/jobs/live.tests.yml
        MatrixConfigs:
          - Name: Cosmos_emulator_integration
            Path: eng/pipelines/templates/stages/cosmos-emulator-matrix.json
            Selection: all
            GenerateVMJobs: true
        MatrixFilters:
          - ${{ parameters.LanguageFilter }}
          - ${{ parameters.MatrixFilters }}
        AdditionalParameters:
          BuildParallelization: 1
          DisableAzureResourceCreation: true
          ServiceDirectory: cosmos
          Artifacts: ${{ parameters.Artifacts }}
          AdditionalModules: ${{ parameters.AdditionalModules }}
          ACCOUNT_HOST: 'https://localhost:8081/'
          ACCOUNT_KEY: 'C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=='
          SECONDARY_ACCOUNT_KEY: 'C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=='
          # Increased timeout to 90 because of cosmos emulator taking 25-30 mins to download emulator
          # Issue filed to improve download speed: https://github.com/Azure/azure-sdk-for-java/issues/12970
          TimeoutInMinutes: 90
          TestGoals: 'clean verify'
          TestOptions: '$(ProfileFlag) $(AdditionalArgs)'

          PreSteps:
          - template: /eng/common/pipelines/templates/steps/cosmos-emulator.yml
            parameters:
              StartParameters: '/noexplorer /noui /enablepreview /EnableSqlComputeEndpoint /SqlComputePort=9999 /disableratelimiting /partitioncount=50 /consistency=Strong'
          - powershell: |
              $Key = 'C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=='
              $password = ConvertTo-SecureString -String $Key -Force -AsPlainText
              $cert = Get-ChildItem cert:\LocalMachine\My | Where-Object { $_.FriendlyName -eq "DocumentDbEmulatorCertificate" }
              Export-PfxCertificate -Cert $cert -FilePath ".\CosmosDbEmulatorCert.pfx" -Password $password | Out-Null
              $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
              $cert.Import(".\CosmosDbEmulatorCert.pfx", $Key, "DefaultKeySet")
              $cert | Export-Certificate -FilePath "$env:temp\CosmosDbEmulatorCert.cer" -Type CERT
            displayName: 'Export Cosmos DB Emulator Certificate'
          - powershell: |
              if (Test-Path $env:JAVA_HOME\jre\lib\security) {
                cd $env:JAVA_HOME\jre\lib\security
              } elseif (Test-Path $env:JAVA_HOME\lib\security) {
                cd $env:JAVA_HOME\lib\security
              } else {
                Write-Error "JDK directory structure is unknown and unsupported. JAVA_HOME is '$env:JAVA_HOME'"
                exit 1
              }
              cp $env:temp\CosmosDbEmulatorCert.cer .
              keytool -keystore cacerts -importcert -noprompt -trustcacerts -alias CosmosDbEmulatorCert -file CosmosDbEmulatorCert.cer -storepass changeit
            displayName: 'Create Java TrustStore'
          - powershell: |
              $downloadTarget = Join-Path -Path $env:temp -ChildPath "hadoopsource.zip"
              $targetDir = "D:\Hadoop"
              Write-Host "Downloading and extracting Hadoop winutils - https://aka.ms/cosmos-hadoop-for-spark-ci-pipeline2"
              Write-Host "Target: $targetDir"
              Invoke-WebRequest "https://aka.ms/cosmos-hadoop-for-spark-ci-pipeline2" -OutFile $downloadTarget
              if (Test-Path $targetDir) { Remove-Item -Recurse -Force $targetDir }
              Expand-Archive -LiteralPath $downloadTarget -DestinationPath $targetDir
              Write-Host "Copying binaries to windows sytem32 folder"
              Copy-Item -Path "D:\Hadoop\bin\*" -Destination "C:\Windows\System32" -Recurse
              Write-Host "Updating environment variables for Hadoop usage"
              [System.Environment]::SetEnvironmentVariable("HADOOP_HOME", "D:\Hadoop", [System.EnvironmentVariableTarget]::Machine)
              $hadoopHome = [System.Environment]::GetEnvironmentVariable("HADOOP_HOME", [System.EnvironmentVariableTarget]::Machine)
              Write-Host "New HADOOP_HOME environment variable: $hadoopHome"
              $path = [System.Environment]::GetEnvironmentVariable("Path", [System.EnvironmentVariableTarget]::Machine)
              Write-Host "Original Path environment variable: $path"
              $newPath = $path + ";D:\Hadoop\bin"
              [System.Environment]::SetEnvironmentVariable("Path", $newPath,[System.EnvironmentVariableTarget]::Machine)
              $updatedPath = [System.Environment]::GetEnvironmentVariable("Path", [System.EnvironmentVariableTarget]::Machine)
              Write-Host "New Path environment variable: $updatedPath"
            displayName: 'Download and Extract Hadoop winutils and update env variables for Hadoop usage'

  # The Prerelease and Release stages are conditioned on whether we are building a pull request and the branch.
  - ${{if and(ne(variables['Build.Reason'], 'PullRequest'), eq(variables['System.TeamProject'], 'internal'))}}:
    - ${{ if eq(parameters.EnableBatchRelease, 'true') }}:
      - template: archetype-java-release-batch.yml
        parameters:
          DependsOn:
            - Build
            - TestEmulator
          ServiceDirectory: ${{ parameters.ServiceDirectory }}
          SDKType: ${{ parameters.SDKType }}
          # By default, the Artifacts list will contain everything as we won't skip an artifact unless it,
          # specifically, has releaseInBatch set to false. releaseInBatch should only be set libraries,
          # not ready for release, in service directories that have batch release enabled. The if statement
          # below, looking for releaseInBatch not equal false has to be set this way because if the library's
          # metadata in the ci.yml doesn't have this variable then it defaults to being released.
          Artifacts:
            - ${{ each artifact in parameters.Artifacts }}:
              - ${{ if ne(artifact.releaseInBatch, 'false') }}:
                - ${{ artifact }}
          TestPipeline: false
          ArtifactName: packages
          TargetDocRepoName: ${{ parameters.TargetDocRepoName }}
          UseEsrpRelease: ${{ parameters.UseEsrpRelease }}
    - ${{ else }}:
      - template: archetype-java-release.yml
        parameters:
          DependsOn:
            - Build
            - TestEmulator
          ServiceDirectory: ${{ parameters.ServiceDirectory }}
          SDKType: ${{ parameters.SDKType }}
          Artifacts: ${{ parameters.Artifacts }}
          ArtifactName: packages
          TargetDocRepoName: ${{ parameters.TargetDocRepoName }}
          UseEsrpRelease: ${{ parameters.UseEsrpRelease }}
