parameters:
  - name: agentVersion
    type: string
    default: "3.240.1"
  - name: vmImage
    type: string
    default: "ubuntu-latest"
  - name: resourceGroup
    type: string
    default: "asdm-agent-rg"
  - name: location
    type: string
    default: "eastus"
  - name: agentCount
    type: number
    default: 2

trigger:
  branches:
    include:
      - main
  paths:
    include:
      - .workspace/azure-pipelines-agent-arm.yml

pr: none

variables:
  - name: agentPoolName
    value: "asdm-arm-agent-pool"
  - name: armTemplateFile
    value: "agent-arm-template.json"
  - name: artifactName
    value: "arm-agent-deployment"

stages:
  - stage: Validate
    displayName: "Validate ARM Template"
    jobs:
      - job: ValidateTemplate
        displayName: "Validate ARM Template"
        pool:
          vmImage: ${{ parameters.vmImage }}
        steps:
          - task: AzureResourceManagerTemplateDeployment@3
            displayName: "Validate ARM Template"
            inputs:
              deploymentScope: "Resource Group"
              azureResourceManagerConnection: "azure-service-connection"
              subscriptionId: "$(azureSubscriptionId)"
              action: "Validate Only"
              resourceGroupName: ${{ parameters.resourceGroup }}
              location: ${{ parameters.location }}
              templateLocation: "Linked artifact"
              csmFile: "$(armTemplateFile)"
              overrideParameters: >
                -agentPoolName "$(agentPoolName)"
                -agentCount ${{ parameters.agentCount }}
                -agentVersion ${{ parameters.agentVersion }}

  - stage: Build
    displayName: "Build Agent Package"
    dependsOn: Validate
    jobs:
      - job: BuildAgent
        displayName: "Build ARM Agent Package"
        pool:
          vmImage: ${{ parameters.vmImage }}
        steps:
          - checkout: self

          - task: Bash@3
            displayName: "Download Azure Pipelines Agent (ARM64)"
            inputs:
              targetType: "inline"
              script: |
                AGENT_VERSION="${{ parameters.agentVersion }}"
                AGENT_URL="https://vstsagentpackage.azureedge.net/agent/${AGENT_VERSION}/vsts-agent-linux-arm64-${AGENT_VERSION}.tar.gz"
                echo "Downloading agent version ${AGENT_VERSION} from ${AGENT_URL}"
                mkdir -p "$(Build.ArtifactStagingDirectory)/agent"
                curl -L -o "$(Build.ArtifactStagingDirectory)/agent/vsts-agent-linux-arm64.tar.gz" "${AGENT_URL}"
                echo "Verifying download..."
                ls -lh "$(Build.ArtifactStagingDirectory)/agent/"

          - task: Bash@3
            displayName: "Extract and Prepare Agent"
            inputs:
              targetType: "inline"
              script: |
                mkdir -p "$(Build.ArtifactStagingDirectory)/agent/extracted"
                tar -xzf "$(Build.ArtifactStagingDirectory)/agent/vsts-agent-linux-arm64.tar.gz" \
                  -C "$(Build.ArtifactStagingDirectory)/agent/extracted"
                echo "Agent contents:"
                ls "$(Build.ArtifactStagingDirectory)/agent/extracted/"

          - task: ArchiveFiles@2
            displayName: "Archive Agent Package"
            inputs:
              rootFolderOrFile: "$(Build.ArtifactStagingDirectory)/agent/extracted"
              includeRootFolder: false
              archiveType: "tar"
              archiveFile: "$(Build.ArtifactStagingDirectory)/agent-arm64-package.tar.gz"
              replaceExistingArchive: true

          - task: PublishBuildArtifacts@1
            displayName: "Publish Agent Artifact"
            inputs:
              pathToPublish: "$(Build.ArtifactStagingDirectory)"
              artifactName: "$(artifactName)"
              publishLocation: "Container"

  - stage: Deploy
    displayName: "Deploy ARM Agent Infrastructure"
    dependsOn: Build
    condition: succeeded()
    jobs:
      - deployment: DeployAgent
        displayName: "Deploy ARM Agent VMs"
        pool:
          vmImage: ${{ parameters.vmImage }}
        environment: "asdm-production"
        strategy:
          runOnce:
            deploy:
              steps:
                - task: DownloadBuildArtifacts@1
                  displayName: "Download Agent Artifact"
                  inputs:
                    buildType: "current"
                    downloadType: "single"
                    artifactName: "$(artifactName)"
                    downloadPath: "$(Pipeline.Workspace)"

                - task: AzureResourceManagerTemplateDeployment@3
                  displayName: "Deploy ARM Template"
                  inputs:
                    deploymentScope: "Resource Group"
                    azureResourceManagerConnection: "azure-service-connection"
                    subscriptionId: "$(azureSubscriptionId)"
                    action: "Create Or Update Resource Group"
                    resourceGroupName: ${{ parameters.resourceGroup }}
                    location: ${{ parameters.location }}
                    templateLocation: "Linked artifact"
                    csmFile: "$(armTemplateFile)"
                    overrideParameters: >
                      -agentPoolName "$(agentPoolName)"
                      -agentCount ${{ parameters.agentCount }}
                      -agentVersion ${{ parameters.agentVersion }}

                - task: AzureCLI@2
                  displayName: "Configure and Register Agents"
                  inputs:
                    azureSubscription: "azure-service-connection"
                    scriptType: "bash"
                    scriptLocation: "inlineScript"
                    inlineScript: |
                      echo "Configuring Azure Pipelines agents in pool: $(agentPoolName)"
                      AGENT_VERSION="${{ parameters.agentVersion }}"
                      for i in $(seq 1 ${{ parameters.agentCount }}); do
                        VM_NAME="asdm-arm-agent-$i"
                        echo "Configuring agent on VM: ${VM_NAME}"
                        az vm run-command invoke \
                          --resource-group ${{ parameters.resourceGroup }} \
                          --name "${VM_NAME}" \
                          --command-id RunShellScript \
                          --scripts "
                            mkdir -p /opt/azp-agent && cd /opt/azp-agent
                            tar -xzf /tmp/agent-arm64-package.tar.gz
                            ./config.sh --unattended \
                              --url '$(adoOrgUrl)' \
                              --auth pat \
                              --token '$(adoPat)' \
                              --pool '$(agentPoolName)' \
                              --agent '${VM_NAME}' \
                              --acceptTeeEula
                            ./svc.sh install
                            ./svc.sh start
                          "
                      done

  - stage: Verify
    displayName: "Verify Agent Deployment"
    dependsOn: Deploy
    condition: succeeded()
    jobs:
      - job: VerifyAgent
        displayName: "Verify Agents are Online"
        pool:
          vmImage: ${{ parameters.vmImage }}
        steps:
          - task: AzureCLI@2
            displayName: "Check Agent Status"
            inputs:
              azureSubscription: "azure-service-connection"
              scriptType: "bash"
              scriptLocation: "inlineScript"
              inlineScript: |
                echo "Verifying agent deployment..."
                for i in $(seq 1 ${{ parameters.agentCount }}); do
                  VM_NAME="asdm-arm-agent-$i"
                  echo "Checking VM: ${VM_NAME}"
                  az vm show \
                    --resource-group ${{ parameters.resourceGroup }} \
                    --name "${VM_NAME}" \
                    --query "provisioningState" \
                    --output tsv
                done
