[CmdletBinding()]
param
(
    
)
$StartTime = Get-Date
function Get-ITDVMwareSharePointSnapshotRequestList {
    [CmdletBinding()]
    Param
    (
        [PSCredential]
        $Credential
    )

    begin {
        If ($Credential) { $InvokeWebRequestParams += @{Credential = $Credential } }
        Else { $InvokeWebRequestParams += @{UseDefaultCredentials = $true } }

        $URL = "https://share.nd.gov/itd/Computer-Systems/Distributed-Systems/VMWare/_api/lists/getbytitle('VMware-Snapshots')/items" + '?$top=10000' + '&$select=ID,Title,DateTime,Duration,Author/Name,Author/Title,Author/EMail,Status,NotifyEmail,AutoExpire,AutoDelete&$expand=Author/Id'
        $InvokeWebRequestParams += @{
            Uri             = $URL;
            Method          = "Get";
            UseBasicParsing = $true;
            Headers         = @{ "Accept" = "application/json;odata=verbose" }
        }
    
        $List = (Invoke-WebRequest @InvokeWebRequestParams) -creplace '"Id":', '"Idx":' | ConvertFrom-Json  
    }

    process {
    
    }

    end {
        $List.d.results
    }
}

$vCenterCredential = Get-AutomationPSCredential -Name 'VMware Auto' 
$SharePointCredential = Get-AutomationPSCredential -Name 'SharePoint IaaS ReadWrite'

Set-PowerCLIConfiguration -DefaultVIServerMode Multiple -ParticipateInCeip $false -Confirm:$false
Connect-VIServer -Server itdvmvc1.nd.gov, itdvmvc2.nd.gov -Credential $vCenterCredential

$SnapshotList = Get-ITDVMwareSharePointSnapshotRequestList -Credential $SharePointCredential
$ListToRemove = $SnapshotList | Where-Object { $_.Status -eq "Expired, Delete Approved" } | Sort-Object AutoDelete

ForEach ($SPRecord in $ListToRemove) {
    $Id = $null
    $VMName = $null
    $SnapName = $null

    $Id = $SPRecord.ID
    $VMName = $SPRecord.Title
    $SnapName = "AutoSnap_" + $Id

    $SnapshotToRemove = Get-Snapshot -Name $SnapName -VM $VMName
    $Datastore = Get-VM $VMName | Get-Datastore
    $ViServer = $SnapshotToRemove.uid.split('@')[1].split(':')[0]

    Write-Warning ($SnapshotToRemove.Name + " for " + $SnapshotToRemove.VM + " on " + $Datastore + " on " + $ViServer)

    try {
        $SnapshotTaskCount = @(Get-Task -Server $ViServer | Where-Object { $_.Name -eq "RemoveSnapshot_Task" -and $_.State -eq "Running" }).count
        Write-Warning $SnapshotTaskCount
        while ($SnapshotTaskCount -ge 1) {
            $timestamp = Get-Date -UFormat "%Y%m%d%H%M%S"
            Write-Warning "[$timestamp]:$SnapshotTaskCount RemoveSnapshot_Task already running, pausing 60 seconds."
            Start-Sleep -Seconds 60

            $timestamp = $null
            $SnapshotTaskCount = @(Get-Task | Where-Object { $_.Name -eq "RemoveSnapshot_Task" -and $_.State -eq "Running" }).count
            Write-Warning $SnapshotTaskCount
        }
        $timestamp = Get-Date -UFormat "%Y%m%d%H%M%S"
        Write-Warning "[$timestamp]:$SnapshotTaskCount RemoveSnapshot_Task already running, starting removal." 
        $SnapshotToRemove | Remove-Snapshot -Confirm:$false
    }
    catch {
        Write-Error "Snapshot Removal failed";
        Write-Error $Error[1];
        exit
    }

    #update SharePoint field
    Write-Verbose "Exactly one match found, updating SharePoint fields named Status and SnapshotTaken"
    $UrlContextInfo = "https://share.nd.gov/itd/computer-systems/distributed-systems/vmware/_api/contextinfo"
    $InvokeWebRequestParams = @{
        Uri             = $UrlContextInfo;
        Method          = "Post";
        UseBasicParsing = $true;
        Credential      = $SharePointCredential;
    }
    $RequestDigest = Invoke-RestMethod @InvokeWebRequestParams
    $RequestDigest = $RequestDigest.GetContextWebInformation.FormDigestValue

    $UrlList = "https://share.nd.gov/itd/computer-systems/distributed-systems/vmware/_api/lists/getbytitle('VMware-Snapshots')"
    $InvokeWebRequestParams = @{
        Uri             = $UrlList;
        UseBasicParsing = $true;
        Credential      = $SharePointCredential;
    }
    $List = Invoke-RestMethod @InvokeWebRequestParams
    $ListItemEntityTypeFullName = $list.entry.content.properties.ListItemEntityTypeFullName

    $UrlListItem = "https://share.nd.gov/itd/computer-systems/distributed-systems/vmware/_api/lists/getbytitle('VMware-Snapshots')/items" + '?$top=10000'
    $InvokeWebRequestParams = @{
        Uri             = $UrlListItem;
        Method          = "Get";
        UseBasicParsing = $true;
        Headers         = @{ "Accept" = "application/json;odata=verbose" };
        Credential      = $SharePointCredential
    }
    $ListItems = ((Invoke-WebRequest @InvokeWebRequestParams) -creplace '"Id":', '"Idx":' | ConvertFrom-Json).d.results

    $header = @{
        "accept"          = "application/json;odata=verbose"
        "X-RequestDigest" = $RequestDigest
        "IF-MATCH"        = '*'
        "X-HTTP-Method"   = "MERGE"
    }

    $UrlItem = "https://share.nd.gov/itd/computer-systems/distributed-systems/vmware/_api/lists/getbytitle('VMware-Snapshots')/items($Id)"
    
    [PSCustomObject]$SetRecord = @{
        "__metadata"    = @{type = $ListItemEntityTypeFullName };
        Status          = 'Removed';
        SnapshotRemoved = [datetime](Get-Date);
    }

    $body = $SetRecord | ConvertTo-Json
    $InvokeWebRequestParams = @{
    
        Uri             = $UrlItem;
        Method          = "Post";
        Body            = $body;
        ContentType     = "application/json;odata=verbose";
        Headers         = $header;
        UseBasicParsing = $true;
        Credential      = $SharePointCredential;
    }
    Invoke-RestMethod @InvokeWebRequestParams
}
Disconnect-VIServer -Server * -Confirm:$false -ErrorAction SilentlyContinue

$DiffTime = [math]::round((4+((Get-Date) - $StartTime).Minutes),0)
$postParams = [PSCustomObject]@{
    AutomationName = "Infra-VMware";
    Action         = 'Deprovisioning';
    Units          = $DiffTime;
    Platform       = 'PowerShell-VMware-SnapshotRemove';
}
Invoke-RestMethod -Uri http://itdnettools.nd.gov/services/automation-tracking.py -Method POST -Body ($postParams | ConvertTo-Json)