<#
.SYNOPSIS
    A short one-line action-based description, e.g. 'Tests if a function is valid'
.DESCRIPTION
    A longer description of the function, its purpose, common use cases, etc.
.NOTES
    Information or caveats about the function e.g. 'This function is not supported in Linux'
.LINK
    Specify a URI to a help page, this will show when Get-Help -Online is used.
.EXAMPLE
    Test-MyTestFunction -Verbose
    Explanation of the function or its result. You can include multiple examples with additional .EXAMPLE lines
#>

function Approve-ITDVMNewBuild {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $True)]
        [string]
        $SCTaskNum,

        [switch]
        $CloseTask,

        [switch]
        $NoTaskUpdates
    )
    
    begin {
        
    }
    
    process {
        # get current user, SCTask, Ritm
        $assignTo = Get-ServiceNowRecord -Table 'User' -Filter @('email', '-eq', ($env:username + "@nd.gov"))
            
        $SCTask = Get-ServiceNowRecord -Table 'Catalog Task' -ID $SCTaskNum
        $RitmNum = $SCTask.request_item.display_value

        $Ritm = Get-ServiceNowRecord -Table 'Requested Item' -ID $RitmNum -IncludeCustomVariable
        
        $ComputerName = ($Ritm.CustomVariable | Where-Object Name -EQ host_name).Value
        $OperatingSystem = ($Ritm.CustomVariable | Where-Object Name -EQ operating_system).Value
        switch (($Ritm.CustomVariable | Where-Object Name -EQ target_platform).Value) {
            'azure' { $target_platform = "Azure" }
            'vmware' { $target_platform = "VMware" }
        }

        # update short description
        If ($NoTaskUpdates -eq $false) {
            $shortdescription = "$target_platform $OperatingSystem VM Build for $ComputerName"
            If ( ($RITM.CustomVariable | Where-Object Name -EQ dr_protection).Value -ne 'No DR') {
                $shortdescription += ", with SRM protection"
            }
            Update-ServiceNowRecord -ID $SCTask.number -Values @{short_description = $shortdescription; assigned_to = $assignTo.name }      
        }

        # search for VM
        switch (($Ritm.CustomVariable | Where-Object Name -EQ "target_platform").Value) {
            'azure' {
                # update task close notes, task customer notes, and ritm customer notes
                $CommentsToAdd = "Azure VM " + $ComputerName + " build completed. `n" + $CommentsForWorkNotes
            }
            'vmware' {
                $VM = Get-VM -Name $ComputerName | Where-Object { $_.ExtensionData.summary.config.ManagedBy.Type -ne "placeholderVm" }
                switch (@($VM).count) {
                    { 0 -or $null } {
                        # no matches
                        Write-Error -Message "Zero VM matches found, ending script" -ErrorAction Stop
                    }
                    { $_ -ne 1 } {
                        # more than one match
                        Write-Error -Message " VM matches found, ending script" -ErrorAction Stop
                    }
                    { 1 } {
                        # add missing tags
                        switch (($Ritm.CustomVariable | Where-Object Name -EQ environment).Value){
                            'Development' {
                                $DtapString = 'Test'
                            }
                            'Test' {
                                $DtapString = 'Test'
                            }
                            'Production' {
                                $DtapString = 'Production'
                            }
                        }

                        $SetITDVMwareTagsParams = @{
                            ComputerName          = $ComputerName;
                            #AppName               = ($Ritm.CustomVariable | Where-Object Name -EQ application_name).Value;
                            Dtap                  = $DtapString;
                            #OperatingSystem       = switch ( ($Ritm.CustomVariable | Where-Object Name -EQ target_os_version_windows).Value) {
                            #    'Windows Server 2019 Datacenter' { "Windows Server 2019 Standard (64-Bit)" }
                             #   'Windows Server 2022 Datacenter' { "Windows Server 2022 Standard (64-Bit)" }
                            #}
                            StartupPriority       = ($Ritm.CustomVariable | Where-Object Name -EQ startup_priority).Value;
                            LicensingRestrictions = ($Ritm.CustomVariable | Where-Object Name -EQ licensing_restrictions).Value;
                        }
                        Set-ITDVMwareVMTag @SetITDVMwareTagsParams

                        $AppNameTag = Get-TagAssignment -Entity $VM -Category AppName -ErrorAction SilentlyContinue
                        If ($AppNameTag) {
                            # move VM to VM folder that matches AppName tag
                            Write-Verbose -Message ("AppName tag " + $AppNameTag.Tag.Name + " found, attempting to move to AppName folder")
                            Move-ITDVMwareVMToAppNameFolder -Name $ComputerName
                            $CommentsForWorkNotes += "VM $ComputerName moved to AppName folder.  "
                        }
                        Else {
                            Write-Warning "Review AppName tag for $ComputerName, required for backups"
                        }

                        If (($Ritm.CustomVariable | Where-Object Name -EQ "dr_protection").value -ne 'No DR') {
                            Write-Warning "SCTask is not Closed.  Review SRM Protection values manually"
                            $AutoCloseTask = $false
                        }
                        Else {
                            $AutoCloseTask = $true
                        }

                        # update task close notes, task customer notes, and ritm customer notes
                        $CommentsToAdd = "VMware VM " + $ComputerName + " build completed. " + $CommentsForWorkNotes
                    }
                }
            }
        }

        If ($NoTaskUpdates -eq $false) {
            Update-ServiceNowRecord -ID $SCTask.number -Values @{work_notes = $CommentsToAdd; close_notes = $CommentsToAdd; } # enter comments into sctask
            Update-ServiceNowRecord -ID $RitmNum -Values @{comments = $CommentsToAdd }

            If ($CloseTask -eq $True -or $AutoCloseTask -eq $True) {
                Update-ServiceNowRecord -ID $SCTask.number -Values @{state = "Closed Complete" }
            }
        }
    }
    
    end {    
    }
}