<#
.SYNOPSIS
    Processes automated server build tasks for Windows machines in ServiceNow, triggered via PowerShell Universal.
.DESCRIPTION
    This script connects to the ServiceNow API, retrieves open catalog tasks that match a specific filter for automated server build tasks,
    and processes them. This script is designed to run as a scheduled task. It can optionally filter tasks by a specific SCTask number.
.PARAMETER SCTaskNum
    The ServiceNow task number to filter the tasks. If not provided, all tasks matching the filter will be processed.
.EXAMPLE
    .\New-ITDWindowsVmBuildTask_Auto.ps1
    This example runs the script and processes all open tasks that match the filter for automated server build tasks.
.EXAMPLE
    .\New-ITDWindowsVmBuildTask_Auto.ps1 -SCTaskNum 'SCTASK0012345'
    This example runs the script and processes only the task with the specified SCTask number.
.NOTES
    Ensure that the ServiceNow instance URL and credentials are correctly configured in the New-ITDServiceNowSession function.
    This script is not supported in Linux.
#>

Param(
    [string]
    $SCTaskNum
)

New-ITDServiceNowSession -Environment Production -Credential $Secret:snow_vmcred

$Filter = 'active=true^short_descriptionSTARTSWITHAutomated Server Build Task for Windows Machine'
$OpenTasks = Get-ITDServiceNowRecord -ItemType 'Catalog Task' -Filter $Filter | Sort-Object Number
If ($PSBoundParameters.ContainsKey("SCTaskNum")) {
    Write-Verbose -Message "SCTaskNum parameter found, value is $SCTaskNum" -Verbose
    $OpenTasks = $OpenTasks | Where-Object { $_.number.value -EQ $SCTaskNum }
}

$AllRitms = [System.Collections.ArrayList]@()

Write-Verbose -Message ("OpenTasks found: " + @($OpenTasks).Count) -Verbose

ForEach ($OpenTask in $OpenTasks) {
    $PSUJob = $null
    $SCTask = $null
    $shortdescription = $null
    $shortdescription_hostname = $null
    $WorkNotesMsg = $null

    $SCTaskNum = $OpenTask.number.Value
    Write-Verbose -Message "Start $SCTaskNum" -Verbose

    try {
        $SCTask = Get-ITDServiceNowRecord -ItemType 'Catalog Task' -Number $SCTaskNum
        $shortdescription = $SCTask.short_description.display_value
        $shortdescription_hostname = $shortdescription.split(' ')[7]
        $Ritm = Get-ITDServiceNowRecord -ItemType 'Request Item' -Number $SCTask.request_item.display_value -IncludeVariableSet
    <#
        If ($AllRitms | Where-Object { $_.number.display_value -EQ $SCTask.request_item.display_value }) {
            Write-Verbose -Message ("Ritm already in memory") -Verbose
            $Ritm = $AllRitms | Where-Object sys_id -EQ $SCTask.request_item.display_value
        }
        Else {
            Write-Verbose -Message "Ritm is not in memory, retrieve it" -Verbose
            $Ritm = Get-ITDServiceNowRecord -ItemType 'Request Item' -Number $SCTask.request_item.display_value -IncludeVariableSet
            $null = $AllRitms.Add($Ritm)
        }
#>
        # check for step messages in SCTask work_notes and determine next step
        switch ($SCTask.work_notes.display_value) {
            { $_ -match "human review" } {
                Write-Verbose -Message "Human review required, skipping" -Verbose
                Break
            }
            { $_ -match "build step 2 complete" } {
                # execute Step 3
                Write-Verbose -Message "Step 2 already complete, starting step 3" -Verbose
                $PSUJob = Invoke-PSUScript -Script "New-ITDWindowsVm_Step3.ps1" -SCTaskNum $SCTaskNum
                #$WorkNotesMsg = ("VMware build Step 3 started.`nPSU Job Id #" + $PSUJob.Id)
                Break
            }
            { $_ -match "build Step 2 started"} {
                Write-Verbose -Message "Step 2 already started, skipping" -Verbose
                Break
            }
            { $_ -match "build step 1 complete" } {
                # execute Step 2
                Write-Verbose -Message "Step 1 already complete, starting Step 2" -Verbose
                # Determine if VMware or Azure and run appropriate build Step 2 function
                switch ( ($Ritm.VariableSet | Where-Object host_name -EQ $shortdescription_hostname).target_platform ) {
                    'azure' {
                        $target_platform = "Azure"
                        Write-Verbose "Invoking PSUScript for Azure Step 2" -Verbose
                        $PSUJob = Invoke-PSUScript -Script "New-ITDWindowsVmAzure_Step2.ps1" -SCTaskNum $SCTaskNum
                        $WorkNotesMsg = ("VMware build Step 2 started.`nPSU Job Id #" + $PSUJob.Id)
                    }
                    'vmware' {
                        $target_platform = "VMware"
                        Write-Verbose "Invoking PSUScript for VMware Step 2" -Verbose
                        $PSUJob = Invoke-PSUScript -Script "New-ITDWindowsVmVMware_Step2.ps1" -SCTaskNum $SCTaskNum
                        $WorkNotesMsg = ("VMware build Step 2 started.`nPSU Job Id #" + $PSUJob.Id)
                    }
                }
                Break
            }
            { $_ -match "build Step 1 started"} {
                Write-Verbose -Message "Step 1 already started, skipping" -Verbose
                Break
            }
            Default {
                # execute Step 1
                Write-Verbose -Message "No step messages found, starting Step 1" -Verbose
                # Determine if VMware or Azure and run appropriate build function
                switch ( ($Ritm.VariableSet | Where-Object host_name -EQ $shortdescription_hostname).target_platform ) {
                    'azure' {
                        $target_platform = "Azure"
                        Write-Verbose "Invoking PSUScript for Azure Step 1" -Verbose
                        $PSUJob = Invoke-PSUScript -Script "New-ITDWindowsVmAzure_Step1.ps1" -SCTaskNum $SCTaskNum
                        $WorkNotesMsg = ("Azure build Step 1 started.`nPSU Job Id #" + $PSUJob.Id)
                    }
                    'vmware' {
                        $target_platform = "VMware"
                        Write-Verbose "Invoking PSUScript for VMware Step 1" -Verbose
                        $PSUJob = Invoke-PSUScript -Script "New-ITDWindowsVmVMware_Step1.ps1" -SCTaskNum $SCTaskNum
                        $WorkNotesMsg = ("VMware build Step 1 started.`nPSU Job Id #" + $PSUJob.Id)
                    }
                }
                Break
            }
        }

        
    }
    catch {
        Write-Error -Message $error[0]
    }
    If($null -eq $WorkNotesMsg){
        # do nothing
    } Else {
        Update-ITDServiceNowRecord -ItemType 'Catalog Task' -Number $SCTaskNum -Values @{work_notes = $WorkNotesMsg }
    }

    Write-Verbose -Message "End $SCTaskNum" -Verbose
}

#>

#Invoke-PSUScript -Name New-ITDWindowsVmVMware_Step1.ps1 -SCTaskNum "SCTASK0310457"



