function Get-ITDVMwareSharePointNetworkList {
    [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('VM Networks')/items" + '?$top=10000' + '&$select=ID,Title,Vlan_Id,CIDR,PA_Zone,Secure,AutoUpdate'
        $InvokeWebRequestParams += @{
            Uri             = $URL
            Method          = "Get"
            Headers         = @{ "Accept" = "application/json;odata=verbose" }
            UseBasicParsing = $true
        }
        
        $List = (Invoke-RestMethod @InvokeWebRequestParams) -creplace '"Id":', '"Idx":' | ConvertFrom-Json  
        #$List = (Invoke-RestMethod -Uri $URL -Method Get -UseDefaultCredentials -headers @{ "Accept" = "application/json;odata=verbose" }) -creplace '"Id":', '"Idx":' | ConvertFrom-Json
    }
    
    process {
        
    }
    
    end {
        $List.d.results
    }
}

function Get-ITDPAInterface {
    [CmdletBinding()]
    Param (
        [string[]]
        $Number
    )
    
    begin {
        #[xml]$RawXmlZones = (Invoke-RestMethod -Uri 'https://itdnettools.nd.gov/rktest/7050zones.py').Content
        $RawXmlZones = (Invoke-RestMethod -Uri 'https://itdnettools.nd.gov/rktest/7050zones.py')
        $Zones = $RawXmlZones.response.result.zone.entry
        $UniversalDenyZones = Get-ITDPAUniversalDenyZone
    }
    
    process {
        $result = @()
        ForEach ($Zone in $Zones) {
            #$Interfaces = $Zone.network.layer3.member | ForEach-Object{$_ -replace 'ae1.'}
            $Interfaces = $Zone.network.layer3.member | ForEach-Object { $_ -replace "ethernet\d/\d\d." }
            If ($Number) {
                $Interfaces = (Compare-Object -ReferenceObject $Interfaces -DifferenceObject $Number -ExcludeDifferent -IncludeEqual).InputObject
            }
            ForEach ($Interface in $Interfaces) {
                $obj = [PSCustomObject]@{
                    Interface = $Interface;
                    Zone      = $Zone.name
                    ZeroTrust = If (@($UniversalDenyZones) -eq $Zone.Name) { $true }Else { $false };
                }
                $result += $obj
            }
        }
    }
    
    end {
        Write-Output $result
    }
}

function Get-ITDPAUniversalDenyZone {
    [CmdletBinding()]
    Param
    (
        
    )

    Begin {
        $Inbound = (((((Invoke-RestMethod -Uri 'http://itdnettools.nd.gov/rktest/7050denyinbound.py?policy=Universal%20Zone%20Deny%20Inbound') -split '[\r\n]+') | Where-Object { $_ -match "<member>" -and $_ -notmatch "any" -and $_ -notmatch "Deny" }) -replace "<member>") -replace "</member>") -Replace "      " | Sort-Object
        $Outbound = (((((Invoke-RestMethod -Uri 'http://itdnettools.nd.gov/rktest/7050denyinbound.py?policy=Universal%20Zone%20Deny%20Outbound') -split '[\r\n]+') | Where-Object { $_ -match "<member>" -and $_ -notmatch "any" -and $_ -notmatch "Deny" }) -replace "<member>") -replace "</member>") -Replace "      " | Sort-Object
    }
    Process {
        $result = Compare-Object -ReferenceObject $Inbound -DifferenceObject $Outbound -IncludeEqual | Sort-Object InputObject
    }
    End {
        Write-Output ($result | Where-Object SideIndicator -EQ '==').InputObject
    }
}

function Set-ITDVMwareSharePointNetworkRecord {
    [CmdletBinding()]
    Param
    (
        [string]
        $Vlan_Id,

        [string]
        $PA_Zone,

        [ValidateSet("True", "False")]
        [string]
        $Secure,

        [PSCredential]
        $Credential
    )

    Begin {
        $UrlContextInfo = "https://share.nd.gov/itd/computer-systems/distributed-systems/vmware/_api/contextinfo"
        $InvokeWebRequestParams = @{
            Uri             = $UrlContextInfo;
            Method          = "Post";
            UseBasicParsing = $true;
        }
        If ($Credential) { $InvokeWebRequestParams += @{Credential = $Credential } }
        Else { $InvokeWebRequestParams += @{UseDefaultCredentials = $true } }
        #$RequestDigest = Invoke-RestMethod -Uri $UrlContextInfo -Method Post -UseDefaultCredentials
        $RequestDigest = Invoke-RestMethod @InvokeWebRequestParams
        $RequestDigest = $RequestDigest.GetContextWebInformation.FormDigestValue
        
        $UrlList = "https://share.nd.gov/itd/computer-systems/distributed-systems/vmware/_api/lists/getbytitle('VM Networks')"
        $InvokeWebRequestParams = @{
            Uri             = $UrlList;
            UseBasicParsing = $true;
        }
        If ($Credential) { $InvokeWebRequestParams += @{Credential = $Credential } }
        Else { $InvokeWebRequestParams += @{UseDefaultCredentials = $true } }
        #$List = Invoke-RestMethod -uri $UrlList -UseDefaultCredentials
        $List = Invoke-RestMethod @InvokeWebRequestParams
        $ListItemEntityTypeFullName = $list.entry.content.properties.ListItemEntityTypeFullName

        $UrlListItem = "https://share.nd.gov/itd/computer-systems/distributed-systems/vmware/_api/lists/getbytitle('VM Networks')/items" + '?$top=10000'
        $InvokeWebRequestParams = @{
            Uri             = $UrlListItem;
            Method          = "Get";
            UseBasicParsing = $true;
            Headers         = @{ "Accept" = "application/json;odata=verbose" }
        }

        If ($Credential) { $InvokeWebRequestParams += @{Credential = $Credential } }
        Else { $InvokeWebRequestParams += @{UseDefaultCredentials = $true } }
        #$ListItems=((Invoke-RestMethod -Uri $UrlListItem -Method Get -UseDefaultCredentials -headers @{ "Accept" = "application/json;odata=verbose" }) -creplace '"Id":', '"Idx":' | ConvertFrom-Json).d.results
        $ListItems = ((Invoke-RestMethod @InvokeWebRequestParams) -creplace '"Id":', '"Idx":' | ConvertFrom-Json).d.results
        
        $header = @{
            "accept"          = "application/json;odata=verbose"
            "X-RequestDigest" = $RequestDigest
            "IF-MATCH"        = '*'
            "X-HTTP-Method"   = "MERGE"
        }
    }
    Process {
        $RecordToModify = $ListItems | Where-Object Vlan_id -EQ $Vlan_Id
        If (@($RecordToModify).count -gt 1) { 
            Write-Warning "More than one result, skipping $Vlan_Id"
        }
        Else {
            $IDtoModify = $RecordToModify.ID

            $UrlItem = "https://share.nd.gov/itd/computer-systems/distributed-systems/vmware/_api/lists/getbytitle('VM Networks')/items($IDtoModify)"

            [PSCustomObject]$SetRecord = @{
                "__metadata" = @{type = $ListItemEntityTypeFullName } 
            }

            If ($PA_Zone) { $SetRecord += @{PA_Zone = $PA_Zone } }
            If ($Secure) { $SetRecord += @{Secure = $Secure } }

            $body = $SetRecord | ConvertTo-Json
            $InvokeWebRequestParams = @{
                Uri             = $UrlItem;
                Method          = "Post";
                Body            = $body;
                ContentType     = "application/json;odata=verbose";
                Headers         = $header;
                UseBasicParsing = $true;
            }

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

            Invoke-RestMethod @InvokeWebRequestParams
        }
    }
    End {
        
    }
}

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

$SharePointList = Get-ITDVMwareSharePointNetworkList -Credential $SharePointCredential

$PAInterfaces = Get-ITDPAInterface -ErrorAction SilentlyContinue # | select *, @{n = 'Vlan_Id'; e = { $_.Interface.PadLeft(4, '0') } }

If ($null -eq $PAInterfaces) {
    
}
Else {
    ForEach ($SPItem in $SharePointList) {
        Write-Warning ($SPItem.Vlan_Id + ", " + $SPItem.CIDR + " - Start")
        $change = $false

        If ($SPItem.AutoUpdate -eq $true) {  
            $SetITDVMwareSharePointVMNetworkParams = $null

            $PAItem = $PAInterfaces | Where-Object Interface -EQ ($SPItem.Vlan_Id -as [int])
            $SetITDVMwareSharePointVMNetworkParams = @{Vlan_Id = $SPItem.Vlan_Id;
                Credential                                     = $SharePointCredential
            }
            If ($PAItem.ZeroTrust) {
                If ($SPItem.Secure -ne $PAItem.ZeroTrust) {
                    $SetITDVMwareSharePointVMNetworkParams += @{Secure = [bool]$PAItem.ZeroTrust }    
                    $change = $true
                }
            }
            Else {
                If ($SPItem.Secure -eq $false) {
                    # Secure is accurate
                }
                Else {
                    $SetITDVMwareSharePointVMNetworkParams += @{Secure = $false }
                    $change = $true
                }
            }

            If ($SPItem.PA_Zone -ne $PAItem.Zone) {
                $SetITDVMwareSharePointVMNetworkParams += @{PA_Zone = $PAItem.Zone }
                $change = $true
            }

            If ($Change -eq $true) {
                Write-Warning ("Set VM network metadata: Vlan " + $SPItem.Vlan_Id + ", " + $SPItem.CIDR)
                Set-ITDVMwareSharePointNetworkRecord @SetITDVMwareSharePointVMNetworkParams
            }
        
        }
    }
}

$postParams = [PSCustomObject]@{
    AutomationName = "Infra-VMware";
    Action         = 'Provisioning';
    Units          = 5;
    Platform       = 'PowerShell-VMware-NetworkSync';
}

Invoke-RestMethod -Uri http://itdnettools.nd.gov/services/automation-tracking.py -Method POST -Body ($postParams | ConvertTo-Json)