[CmdletBinding()]
param (
    [Parameter(Mandatory = $false)]
    [object]
    $WebhookData
)

function Get-ITDVMwareSharePointSnapshotRequestList {
    [CmdletBinding()]
    Param
    (
        [PSCredential]
        $Credential
    )

    begin {
        $InvokeWebRequestParams = @{ }
        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
$ListToUpdate = $SnapshotList | where-object { $_.Status -eq "Scheduled" } | Sort-Object DateTime

#$VM = Get-VM -Name $VMName | where-object { $_.ExtensionData.summary.config.ManagedBy.Type -ne "placeholderVm" }
#If (@($VM).count -eq 2) { $VM = Get-VM -Name $VMName -Server ($global:DefaultVIServers | Sort-Object Name | select -first 1).Name }

ForEach($SPRecord in $ListToUpdate)
{
    $VM = $null
    $Taken = $null
    $VMName = $null
    $Duration = $null
    $Id = $null
    $VMSnapshot = $null
    $Task = $null

    If( (($SPRecord.DateTime) -as [datetime]).ToLocalTime() -lt (Get-Date) ) # If datetime has passed
    {
        $VMName = $SPRecord.Title
        $VM = Get-VM -Name $VMName | where-object { $_.ExtensionData.summary.config.ManagedBy.Type -ne "placeholderVm" }
        $Duration = $SPRecord.Duration
        $Id = $SPRecord.Id

        switch ($Duration) {
            {$Duration -ge 1 -and $Duration -le 7}
                {
                    Write-Verbose "Duration = Snapshot"
                    $VMSnapshots = $VM | Get-Snapshot | where-object Description -like "AutoSnap_$Id*"

                    If (@($VMSnapshots).count -eq 1) {
                        Write-Verbose "Exactly one snapshot match found"
                        $Taken = $true
                        $VMSnapshot = $VMSnapshots
                        $Task = ((Get-View ((Get-View ScheduledTaskManager).ScheduledTask)).info | where-object Description -like "AutoSnap_$Id*")
                    }
                    else {
                        if (@($VMSnapshots).count -gt 1) {
                            Write-Error "More than one snapshot match found, abort"
                            Exit
                        }
                        else {
                            $Taken = $false
                            Write-Verbose "Snapshot Id #$Id match not found on $VMName"
                            Write-Error "Snapshot $Id for $VMName not found."
                        }
                    }
                }
            {$Duration -ge 8}
                {
                    Write-Verbose "Duration = Clone"
                    $VMClones = Get-VM | Where-Object Name -eq ($VMName + "_AutoClone_" + $Id)

                    If (@($VMClones).count -eq 1) {
                        Write-Verbose "Exactly one clone match found"
                        $Taken = $true
                        $VMClone = $VMClones
                        $Task = ((Get-View ((Get-View ScheduledTaskManager).ScheduledTask)).info | where-object Description -like "AutoClone_$Id*")
                    }
                    else {
                        if (@($VMClones).count -gt 1) {
                            Write-Error "More than one VM clone match found, abort"
                            Exit
                        }
                        else {
                            $Taken = $false
                            Write-Verbose "Clone Id #$Id match not found for $VMName"
                            Write-Error "Clone $Id for $VMName not found."
                        }
                    }
                }
            Default {
                Write-Error "Duration less than zero."
            }
        }
                        
        
        write-verbose "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)"
        $InvokeWebRequestParams = @{
            Uri             = $UrlItem;
            Method          = "Get";
            Headers         = @{ "Accept" = "application/json;odata=verbose" }
            UseBasicParsing = $true;
            Credential      = $SharePointCredential
        }

        [PSCustomObject]$SetRecord = @{
            "__metadata"  = @{type = $ListItemEntityTypeFullName };
            #Status        = 'Taken';
            Status        = If ($Taken -eq $true) {'Taken'} Else {'Errored'};            
            SnapshotTaken = $Task.PrevRunTime;
            AutoExpire    = ($Task.Description -split '[\r\n]+')[1].split('_')[1];
            AutoDelete    = ($Task.Description -split '[\r\n]+')[2].split('_')[1];

        }
            
        $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
    }
}

$postParams = [PSCustomObject]@{
    AutomationName = "Infra-VMware";
    Action = 'Provisioning';
    Units = 1;
    Platform = 'PowerShell-VMware-SnapshotUpdateStatus';
}
Invoke-RestMethod -Uri http://itdnettools.nd.gov/services/automation-tracking.py -Method POST -Body ($postParams | ConvertTo-Json)

Disconnect-VIServer * -Confirm:$false -ErrorAction SilentlyContinue