AdoUtils.psm1

Import-Module $PSScriptRoot\PsHelper.psm1
Import-Module $PSScriptRoot\Utils.psm1
Import-Module $PSScriptRoot\WinBuildUtils.psm1

function Get-AdoAgent {
    param(
        [string]$ComputerName = (hostname),
        [pscredential]$Credential = [pscredential]::Empty,
        [string][Parameter(Mandatory = $true)]$AgentUrl,
        [string][Parameter(Mandatory = $true)]$AgentZip
    )

    
    Write-TraceLog "Get-AdoAgent: Fetching agent from $AgentUrl"

    $downloadScript = {
        param(
            [string]$agentUrl,
            [string]$agentZip
        )

        Start-BitsTransfer $agentUrl -destination $agentZip
    }

    Invoke-ReliableCommand -computerName $ComputerName -credential $Credential -scriptblock $downloadScript -argumentList @($AgentUrl, $AgentZip)

}

function Get-AdoInstallPat {
    $pat = $env:ADO_PAT

    if ([String]::IsNullOrEmpty($pat)) {
        throw ("AdoPat is not set")
    }

    return $pat
}

function Install-AdoAgent {
    param(
        [string]$ComputerName = (hostname),
        [pscredential]$Credential = [pscredential]::Empty,
        [string]$AgentUrl,
        [pscredential]$RunAsCred = [pscredential]::Empty
    )

    $agentZip = "c:\agent.zip"
    $installLocation = "c:\agent"
    $prepareScriptBlock = {
        param(
            [string]$agentZip,
            [string]$installLocation
        )
        Remove-Item $agentZip -Force -ErrorAction SilentlyContinue
        Stop-Service vstsagent* -ErrorAction SilentlyContinue -Force
        Remove-Item $installLocation -Force -Recurse -ErrorAction SilentlyContinue
        New-Item -ItemType Directory -Force -Path $installLocation
    }

    Invoke-ReliableCommand -computerName $ComputerName -credential $Credential -scriptblock $prepareScriptBlock -argumentList @($agentZip, $installLocation)

    Get-AdoAgent -AgentUrl $AgentUrl -AgentZip $agentZip -computerName $ComputerName -credential $Credential

    if ($runAsCred -eq [pscredential]::Empty) {
        $runAsCred = Get-WttNAOCred
    }

    $pat = Get-AdoInstallPat

    $installScript = {
        param(
            [string]$agentZip,
            [string]$installLocation,
            [string]$pat,
            [pscredential]$runAsCred
        )
        try {
            
            Push-Location $installLocation

            $username = $runascred.UserName
            $password = $runAsCred.GetNetworkCredential().Password

            Expand-Archive -Path $agentZip -DestinationPath $installLocation -Force

            $configScript = Join-Path $installLocation "config.cmd"
            
            $params = @(
                "--unattended",
                "--url https://microsoft.visualstudio.com/",
                "--auth pat",
                "--token $pat",
                "--pool WindowsSDN",
                "--acceptTeeEula",
                "--replace",
                "--runAsService",
                "--windowsLogonAccount $username",
                "--windowsLogonPassword $password"
            )

            $params = " " + ($params -Join " ")
            $cmd = $configScript + $params

            $bytes = [Text.Encoding]::Unicode.GetBytes($cmd)
            $encodedCommand = [Convert]::ToBase64String($bytes)
            $result = powershell.exe -noprofile -encodedCommand $encodedCommand
            return $result

        }
        finally {
            Pop-Location
        }
    }

    Write-TraceLog "Install-AdoAgent: Configuring agent on $ComputerName. RunAsAccount: $($runAsCred.UserName)"

    Invoke-ReliableCommand -computerName $ComputerName -credential $Credential -scriptblock $installScript `
        -argumentList @($agentZip, $installLocation, $pat, $runAsCred)
}