# This job template uses the artifact list in the ci.yml file
# to generate a variable at build time that can be passed into
# the Maven -pl command-line switch to constrain what subset of
# projects are targeted based on the artifacts this pipeline
# produces. The -am and -amd switches are then applied as
# appropriate to constrain the full graph that is built depending
# on whether we are doing a recorded test play back or a full live
# test.

# The project list is also being used as a cache key.
parameters:
  - name: Artifacts
    type: object
    default: []
  - name: AdditionalModules
    type: object
    default: []
  - name: JobType
    type: string
    default: test
  - name: UseCache
    type: boolean
    default: true

steps:
  # Create the ProjectList and ProjectListSha256 variables.
  # The ProjectList is used by subsequent steps and tasks to run CI.
  # The ProjectListSha256 is used by the cache key, previously the cache key was using ProjectList but it was found
  # that long cache keys cause caching to fail.
- pwsh: |
    $artifacts = '${{ convertToJson(parameters.Artifacts) }}' | ConvertFrom-Json
    $additionalModules = '${{ convertToJson(parameters.AdditionalModules) }}' | ConvertFrom-Json

    $projectList = @()
    foreach ($artifact in $artifacts) {
      $projectList += "$($artifact.groupId):$($artifact.name)"
    }
    foreach ($artifact in $additionalModules) {
      $projectList += "$($artifact.groupId):$($artifact.name)"
    }
    $projects = $projectList -join ','

    Write-Host "ProjectList = $projects"
    Write-Host "##vso[task.setvariable variable=ProjectList;]$projects"

    $sha256 = new-object -TypeName System.Security.Cryptography.SHA256Managed
    $utf8 = new-object -TypeName System.Text.UTF8Encoding

    $projectListSha256 = [Convert]::ToBase64String($sha256.ComputeHash($utf8.GetBytes($projects)))
    Write-Host "##vso[task.setvariable variable=ProjectListSha256;]$projectListSha256"
  displayName: Initialize project list variable

# The Cache task, when restoring, can have a miss and still pass but, if nothing is built, the
# Post-Job Cache will fail because there's no .m2/repository
- ${{ if eq(parameters.UseCache, 'true') }}:
  - task: Cache@2
    inputs:
    # Note: CacheSalt is only intended to be used in special cases, as a build is queued, to force a cache miss.
    # This would be set as a variable in the UI when the run is queued.
      key: 'maven | "$(CacheSalt)" | "$(Agent.OS)" | $(Build.SourcesDirectory)/eng/versioning/external_dependencies.txt | "$(ProjectListSha256)" | "${{ parameters.JobType }}" | "$(TestFromSource)"'
      path: $(MAVEN_CACHE_FOLDER)
    displayName: Cache Maven local repo
