trigger:
  branches:
    include:
      - main
      - release/*

pr: none

parameters:
  - name: agentCount
    displayName: "Number of agents to deploy"
    type: int
    default: 1
  - name: vmSize
    displayName: "VM size for agents"
    type: string
    default: "Standard_D2s_v3"
  - name: location
    displayName: "Azure region"
    type: string
    default: "eastus"
  - name: environment
    displayName: "Environment tag"
    type: string
    default: "dev"

variables:
  - name: resourceGroupName
    value: "rg-azure-pipelines-agent-$(parameters.environment)"
  - name: agentPoolName
    value: "SelfHosted-Agent-Pool"
  - name: azureSubscription
    value: "azure-service-connection"
  - name: vmImage
    value: "ubuntu-2204-lts"
  - group: agent-deploy-vars

stages:
  - stage: Validate
    displayName: "Validate ARM Template"
    jobs:
      - job: ValidateTemplate
        displayName: "Validate ARM Template"
        steps:
          - task: AzureResourceManagerTemplateDeployment@3
            displayName: "Validate ARM Template"
            inputs:
              deploymentScope: "Resource Group"
              azureResourceManagerConnection: "$(azureSubscription)"
              subscriptionId: "$(subscriptionId)"
              action: "Validate"
              resourceGroupName: "$(resourceGroupName)"
              location: "$(parameters.location)"
              templateLocation: "Linked artifact"
              csmFile: "arm-template/template.json"
              csmParametersFile: "arm-template/parameters.json"
              overrideParameters: >
                -agentCount $(parameters.agentCount)
                -vmSize $(parameters.vmSize)
                -location $(parameters.location)
                -environment $(parameters.environment)

  - stage: Deploy
    displayName: "Deploy Agent Infrastructure"
    dependsOn: Validate
    condition: succeeded()
    jobs:
      - deployment: DeployARM
        displayName: "Deploy ARM Template"
        environment: "agent-deploy"
        strategy:
          runOnce:
            deploy:
              steps:
                - task: AzureResourceManagerTemplateDeployment@3
                  displayName: "Deploy ARM Template"
                  inputs:
                    deploymentScope: "Resource Group"
                    azureResourceManagerConnection: "$(azureSubscription)"
                    subscriptionId: "$(subscriptionId)"
                    action: "Create Or Update Resource Group"
                    resourceGroupName: "$(resourceGroupName)"
                    location: "$(parameters.location)"
                    templateLocation: "Linked artifact"
                    csmFile: "arm-template/template.json"
                    csmParametersFile: "arm-template/parameters.json"
                    overrideParameters: >
                      -agentCount $(parameters.agentCount)
                      -vmSize $(parameters.vmSize)
                      -location $(parameters.location)
                      -environment $(parameters.environment)
                    deploymentMode: "Incremental"

                - task: AzureCLI@2
                  displayName: "Configure Self-Hosted Agent"
                  inputs:
                    azureSubscription: "$(azureSubscription)"
                    scriptType: "bash"
                    scriptLocation: "inlineScript"
                    inlineScript: |
                      echo "Configuring self-hosted Azure Pipelines agent..."
                      AGENT_TOKEN=$(az keyvault secret show \
                        --name "agent-token" \
                        --vault-name "$(keyVaultName)" \
                        --query value -o tsv)

                      for i in $(seq 1 $(parameters.agentCount)); do
                        VM_NAME="azp-agent-$(parameters.environment)-$i"
                        echo "Installing agent on $VM_NAME..."
                        az vm run-command invoke \
                          --resource-group "$(resourceGroupName)" \
                          --name "$VM_NAME" \
                          --command-id "RunShellScript" \
                          --scripts "@scripts/install-agent.sh" \
                          --parameters \
                            poolName="$(agentPoolName)" \
                            agentToken="$AGENT_TOKEN" \
                            vmName="$VM_NAME"
                      done

  - stage: Verify
    displayName: "Verify Agent Registration"
    dependsOn: Deploy
    condition: succeeded()
    jobs:
      - job: VerifyAgents
        displayName: "Verify Agent Pool"
        steps:
          - task: AzureCLI@2
            displayName: "Check Agent Pool Status"
            inputs:
              azureSubscription: "$(azureSubscription)"
              scriptType: "bash"
              scriptLocation: "inlineScript"
              inlineScript: |
                echo "Verifying agents in pool $(agentPoolName)..."
                ORG_URL="$(azDevOpsOrgUrl)"
                PAT_TOKEN=$(az keyvault secret show \
                  --name "devops-pat" \
                  --vault-name "$(keyVaultName)" \
                  --query value -o tsv)

                AGENTS=$(curl -s -u ":$PAT_TOKEN" \
                  "${ORG_URL}/_apis/distributedtask/pools?poolName=$(agentPoolName)&api-version=6.0" \
                  | jq -r '.value[0].agents | length')

                echo "Number of registered agents: $AGENTS"
                if [ "$AGENTS" -lt "$(parameters.agentCount)" ]; then
                  echo "WARNING: Expected $(parameters.agentCount) agents, found $AGENTS"
                  exit 1
                fi
                echo "All agents registered successfully."

          - task: AzureCLI@2
            displayName: "Health Check - Agent Connectivity"
            inputs:
              azureSubscription: "$(azureSubscription)"
              scriptType: "bash"
              scriptLocation: "inlineScript"
              inlineScript: |
                echo "Running agent connectivity health check..."
                for i in $(seq 1 $(parameters.agentCount)); do
                  VM_NAME="azp-agent-$(parameters.environment)-$i"
                  STATUS=$(az vm list \
                    --resource-group "$(resourceGroupName)" \
                    --query "[?name=='$VM_NAME'].powerState" \
                    -o tsv)
                  echo "VM $VM_NAME status: $STATUS"
                  if [ "$STATUS" != "VM running" ]; then
                    echo "WARNING: $VM_NAME is not running"
                    exit 1
                  fi
                done
                echo "Health check passed."
