# used by both Azure and VMware build tasks

[CmdletBinding()]
Param(
    [Parameter(Mandatory = $true, ParameterSetName = 'FromSCTASK')]
    [string]
    $SCTaskNum,

    [Parameter(Mandatory = $true, ParameterSetName = 'ManualEntry')]
    [string]
    $FQDN
)

# get FQDN from SCTask/Ritm, or directly from user input
switch ($PSCmdlet.ParameterSetName) {
    'ManualEntry' {
        Write-Verbose -Message "FQDN manually entered"
    }
    'FromSCTask' {
        Write-Verbose -Message ("UAJob.ComputerName = " + $UAJob.ComputerName) -Verbose
        switch ($UAJob.ComputerName) {
            "ITDWINAUTOT1" { $ServiceNowEnvironment = 'Test' }
                
            "ITDWINAUTOP1" { $ServiceNowEnvironment = 'Production' }
        }
        New-ITDServiceNowSession -Environment $ServiceNowEnvironment -Credential $Secret:snow_vmcred
    
        $SCTask = Get-ITDServiceNowRecord -ItemType 'Catalog Task' -Number $SCTaskNum
        $Ritm = Get-ITDServiceNowRecord -ItemType 'Request Item' -SysId ($SCTask.request_item.value) -IncludeVariableSet -IncludeCustomVariable
        Write-Verbose -Message ("Ritm: " + $Ritm.Number) -Verbose
    
        $FqdnFromSCTaskDescription = ($SCTask.short_description).display_value.split(' ')[7]
        Write-Verbose -Message ("FqdnFromSCTaskDescription: " + ($SCTask.short_description).display_value.split(' ')[7]  ) -Verbose
        
        $FQDN = ( ($Ritm.VariableSet | Where-Object { $_.host_name -eq $FqdnFromSCTaskDescription }).host_name ).tolower();
        $OperatingSystem = ($Ritm.VariableSet | Where-Object host_name -EQ $shortdescription_hostname).operating_system
    }
}

try {
    switch ( ($Ritm.VariableSet | Where-Object host_name -EQ $shortdescription_hostname).target_platform ) {
        'azure' { $target_platform = "Azure" }
        'vmware' { $target_platform = "VMware" }
    }
<#  Is this needed?
    $Ci = Get-ITDServiceNowRecord -Table cmdb_ci -Filter ("name=" + $FormHostName)
    If ($Ci) {
        Write-Verbose -Message ("Ci found, sys_id = " + $Ci.sys_id + ", name = " + $Ci.name + ", fqdn = " + $Ci.fqdn) -Verbose
    }
    Else {
        # Ci does not exist
        Write-Verbose -Message ("Ci not found") -Verbose
    }
    
    switch ($Ci.model_id.display_value) {
        { $_ -like "*VMware*" } { $hardware_platform = "VMware"; $hardware_type = 'Virtual Machine' }
        { $_ -like "*Microsoft Virtual Machine*" } { $hardware_platform = "Azure"; $hardware_type = 'Virtual Machine' }
        { $_ -like "*HP*" } { $hardware_platform = 'HPE'; $hardware_type = 'Physical' }
        default { $hardware_platform = 'Other' }
    }
#>
    Write-Verbose -Message "Confirm all required agents are running"
    $ProcessList = @('ccmexec', 'cohesity*', 'nessus*', 'cortex*')
    switch ($target_platform) {
        'VMware' {
            $ProcessList += 'vmtoolsd'
        }
        'Azure' {
            Write-Verbose -Message "No Azure specific agents to check for" -Verbose
        }
        Default {
            Write-Verbose -Message "no Ci means no platform check"
        }
    }
}
catch {
    Write-Error $error[0]
}

If ( $FQDN -like "*.nd.gov" ) {
    try {
        $AgentCount = 0
        $svcitdpsuwin = Get-ITDPassword -UserName ndgov\svcitdpsuwin -Title ndgov\svcitdpsuwin
        $RunningProcess = Invoke-Command -Credential $svcitdpsuwin -ComputerName $FQDN -ErrorAction Stop -ScriptBlock {
            Get-Process
        }
        
        If ($RunningProcess) {
            ForEach ($ProcessName in $ProcessList) {
                If ($RunningProcess -match $ProcessName) {
                    Write-Verbose -Message "Process $ProcessName found." -Verbose
                    $AgentCount = $AgentCount + 1
                }
                Else {
                    Write-Warning -Message "Process $ProcessName not found"
                    # do not increase agentcount count
                }
            }
        } 
    }
    catch [System.Management.Automation.Remoting.PSRemotingTransportException] {
        Write-Warning -Message "$FQDN unreachable via PSRemoting"
        $BuildComplete = $false
    }
}
Else {
    Write-Verbose -Message ($SCTaskNum + $ComputerName + " is not nd.gov, manual agent validation required.") -Verbose
}

If ($AgentCount -ge @($ProcessList).count) {
    Write-Verbose "All required processes running, Windows is ready for use.  Update SCTask to notify physical/virtual hardware stakeholders." -Verbose
    $work_notes = ("$target_platform $hardware_type $FQDN Windows Guest OS complete.  `nPSU Job Id #" + $UAJob.Id)
    $shortdescription = "$target_platform $hardware_type $FQDN Windows Guest OS complete."            

    Write-Verbose -Message "Work notes: $work_notes" -Verbose
    Write-Verbose -Message "Short description: $shortdescription" -Verbose
        
    Update-ITDServiceNowRecord -ItemType 'Catalog Task' -Number $SCTaskNum -Values @{
        work_notes        = $work_notes;
        close_notes       = "$FQDN $target_platform Windows Guest OS complete.";
        short_description = $shortdescription;
        state             = 'Closed Complete'
    }
}

Write-Verbose -Message "End   $SCTasknum" -Verbose
