steps:
- task: PowerShell@2
  displayName: Create Agent Capabilities Variables
  env:
    SYSTEM_ACCESSTOKEN: $(System.AccessToken)
  inputs:
    targetType: inline
    script: |
      [string]$CollectionUri = $env:SYSTEM_COLLECTIONURI
      [string]$AgentId = $env:AGENT_ID
      [string]$AgentName = $env:AGENT_NAME
      [string]$AccessToken = $env:SYSTEM_ACCESSTOKEN

      Function Get-AzureDevopsAgent() {
        param(
          [Parameter(Mandatory = $true)] [string]$baseUri,
          [Parameter(Mandatory = $true)] [int]$agentId,
          [Parameter(Mandatory = $true)] [string]$agentName,
          [Parameter(Mandatory = $true)] [string]$accessToken
        )

        try {
          [Net.ServicePointManager]::SecurityProtocol = "Tls12, Tls13"

          $headers = @{
            Authorization = "Bearer $accessToken"
          }

          $uri = "$($baseUri)/distributedtask/pools?api-version=6.0"
          $responsePools = Invoke-RestMethod -Method Get -Uri $uri -Headers $headers -UseBasicParsing

          foreach ($pool in $responsePools.Value) {
            $uri = "$($baseUri)/distributedtask/pools/$($pool.Id)/agents?api-version=6.0&includeCapabilities=true"
            $responseAgents = Invoke-RestMethod -Method Get -Uri $uri -Headers $headers -UseBasicParsing

            $agents = $responseAgents.Value.Where({$_.id -eq $agentId -and $_.name -eq $agentName})
            if (!($agents) -or $agents.Count -eq 0) {
              continue
            }

            if ($agents.Count -gt 1) {
              throw "Multiple agents ($($agents.Count)) found with id: $agentId and name: $agentName"
            }

            return $agents.Item(0)
          }

          Write-Host -ForeGroundColor Yellow 'Agent NOT found'
          return $null
        }
        catch {
          Write-Host -ForeGroundColor Red 'Unhandled exception occurred during agent fetch!'
          Write-Host -ForegroundColor Red $_.Exception.Message
          throw 
        }
      }

      Function Create-AgentCapabilitiesVariables() {
        param(
          [Parameter(Mandatory = $true)] [PSCustomObject]$capabilities,
          [Parameter(Mandatory = $true)] [string]$capabilityType
        )

        [int]$count = 0
        foreach ($capability in $capabilities.PSObject.Properties) {
          $envName = "AGENT_$($capabilityType)_$($capability.Name)".ToUpper()
          Write-Host "##vso[task.setvariable variable=$envName;]$($capability.Value)"

          $count = $count + 1
        }

        Write-Host -ForeGroundColor Cyan "Created $count AGENT_$capabilityType environment variable(s)"
      }

      if ($CollectionUri.EndsWith('/')) {
          $CollectionUri = $CollectionUri.TrimEnd('/')
      }

      $agentData = Get-AzureDevopsAgent -baseUri "$($CollectionUri)/_apis" -agentId $AgentId -agentName $AgentName -accessToken $AccessToken
      if ($agentData) {
          #Create-AgentCapabilitiesVariables -capabilities $agentData.systemCapabilities -capabilityType 'SYSTEM'
          Create-AgentCapabilitiesVariables -capabilities $agentData.userCapabilities -capabilityType 'USER'
      }
    pwsh: true
