[CmdletBinding()]
param (
    [string]
    $VMName,
    
    [int]
    $Id,

    [switch]
    $WhatIf
)

$PSUJobId = $UAJob.Id

Write-Verbose -Message "Connect to vCenter" -Verbose
Connect-ITDvCenter -Credential $Secret:ndgov_svcitdvmsnapmgr

Write-Verbose -Message "Prepare variables / SQL connection based on PSU server" -Verbose

switch($UAJob.ComputerName){
    "ITDWINAUTOT1" {
        $ServerInstance = "itdintsql22p1.nd.gov\INTSQL22P1"
        $Database = "ITD-Systems-Automation"
        $SnapshotTable = "Infra_VMware_VirtualMachine_VMSnapshots_NPD"
    }
    "ITDWINAUTOP1" {
        $ServerInstance = "itdintsql22p1.nd.gov\INTSQL22P1"
        $Database = "ITD-Systems-Automation"
        $SnapshotTable = "Infra_VMware_VirtualMachine_VMSnapshots_PRD"
    }
}

# find all VMs, with VMName if entered
If ($PSBoundParameters.ContainsKey('VMName')) {
    Write-Verbose -Message "VMName parameter found $VMName" -Verbose
    $VMs = Get-VM -Name $VMName | Where-Object { $_.ExtensionData.summary.config.ManagedBy.Type -ne "placeholderVm" }
}
Else {
    $VMs = Get-VM | Where-Object { $_.ExtensionData.summary.config.ManagedBy.Type -ne "placeholderVm" }
}

# find expired snapshots of the VMs
If ($PSBoundParameters.ContainsKey('Id')) {
    Write-Verbose -Message "ID parameter found $Id" -Verbose
    $AllSnapshots = $VMs | Get-Snapshot | Where-Object Name -EQ "AutoSnap_$Id"
}
Else {
    $AllSnapshots = $VMs | Get-Snapshot | Where-Object Name -Like "AutoSnap_2*" ##### Remove the '2' after SharePoint snapshots are all deleted
}

ForEach ($Snapshot in $AllSnapshots) {
    Write-Verbose -Message ("Start Snapshot " + $Snapshot.Description) -Verbose
    $SnapshotObj = $null

    $SnapshotObj = $Snapshot.Description | ConvertFrom-Json
    If ($null -ne $SnapshotObj -and $SnapshotObj.Expire -lt (Get-Date)) {
        # remove snapshot if expired
        If ($WhatIf) {
            Write-Verbose -Message ("What if: Performing the operation Remove-Snapshot on Snapshot " + $Snapshot.Name) -Verbose
        }
        Else {
            Write-Verbose -Message ("VMName: " + $Snapshot.VM.Name + " / Snapshot ID: " + $SnapshotObj.Id + " -- attempting removal") -Verbose            
            
            # update SQL status to "Delete-Attempted"
            $SqlQueryUpdate = ("UPDATE [$SnapshotTable] SET Status = 'Delete-AutoAttempt', PSUJobIdDelete = '$PSUJobId' WHERE ID = " + $Snapshot.Name.split('_')[1])
            Invoke-Sqlcmd -ServerInstance $ServerInstance -Database $Database -Query $SqlQueryUpdate -Credential $Secret:sql_itdpsu1 -Verbose

            # Remove Snapshot
            $Snapshot | Remove-Snapshot -Confirm:$false -Verbose

            # confirm snapshot is truly gone, then update sql with results
            If (Get-VM -Name $Snapshot.VM.Name | Get-Snapshot -Id $SnapshotObj.Id -ErrorAction SilentlyContinue) {
                $RemoveStatus = $false
            }
            Else {
                # snapshot does not exist
                $RemoveStatus = $true
            }

            # update SQL
            switch ($RemoveStatus) {
                $true {
                    $SqlQueryUpdate = ("UPDATE [$SnapshotTable] SET Status = 'Deleted-AutoSuccess' WHERE ID = " + $Snapshot.Name.split('_')[1])
                }
                $false {
                    $SqlQueryUpdate = ("UPDATE [$SnapshotTable] SET Status = 'Deleted-AutoFailure' WHERE ID = " + $Snapshot.Name.split('_')[1])
                }
            }
            
            Invoke-Sqlcmd -ServerInstance $ServerInstance -Database $Database -Query $SqlQueryUpdate -Credential $Secret:sql_itdpsu1 -Verbose
        }
    }
    Else {
        # do nothing
        Write-Verbose -Message ("VMName: " + $Snapshot.VM.Name + " / Snapshot ID: " + $SnapshotObj.Id + " has not expired.") -Verbose
    }
}

Disconnect-ITDvCenter