PSSubnetCarver.WindowsPowerShell.psm1

if ($PSVersionTable.PSVersion.Major -gt 5) {
    Write-Warning -Message "This module was written for Windows PowerShell, and will note get feature updates. To install the .NET Core version, please uninstall this module and run Install-Module -Name PSSubnetCarver"
}

<#
.SYNOPSIS
 Import a PSSubnetCarver context from a file on disk, or from Azure blob storage.
 
.DESCRIPTION
 Import a PSSubnetCarver context from a .json file either stored on disk, or stored in Azure blob storage. If in Azure blob storage, it will be downloaded via the REST API using a SAS token.
 
.PARAMETER Path
 The path of the .json file that contains the stored information about the context.
 
.PARAMETER Json
 The JSON of the object.
 
.PARAMETER StorageAccountName
 The name of the Azure storage account.
 
.PARAMETER ContainerName
 The name of the container in the Azure storage account.
 
.PARAMETER SASToken
 The SAS token to use when making the REST request.
 
.PARAMETER ContextName
 The name of the context to identify which .json file to download from Azure.
#>

function Import-SCContext {
    [CmdletBinding(DefaultParameterSetName = "FromFile")]
    Param(
        [Parameter(Mandatory = $true, Position = 0, ParameterSetName = "FromFile")]
        [ValidateScript( {
                if (-not (Test-Path -Path $_ -PathType Leaf)) {
                    throw "File not found at $_"
                }

                return $true
            })]
        [string]$Path,

        [Parameter(Mandatory = $true, Position = 0, ParameterSetName = "FromJson")]
        [string]$Json,

        [Parameter(Mandatory = $true, Position = 0, ParameterSetName = "FromAzure")]
        [string]$StorageAccountName,

        [Parameter(Mandatory = $true, Position = 1, ParameterSetName = "FromAzure")]
        [string]$ContainerName,

        [Parameter(Mandatory = $true, Position = 2, ParameterSetName = "FromAzure")]
        [string]$SASToken,

        [Parameter(Mandatory = $false, Position = 3, ParameterSetName = "FromAzure")]
        [string]$ContextName = "default"
    )

    if ($PSCmdlet.ParameterSetName -eq "FromFile") {
        $model = Get-Content -Path $Path -Raw -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop
    }
    elseif ($PSCmdlet.ParameterSetName -eq "FromJson") {
        $model = $Json | ConvertFrom-Json
    }
    elseif ($PSCmdlet.ParameterSetName -eq "FromAzure") {

        $fileName = "$($ContextName.ToLower()).json"

        $filePath = Join-Path -Path $env:TEMP -ChildPath $fileName -ErrorAction Stop

        $blobDownloadParams = @{
            URI         = "https://$($StorageAccountName).blob.core.windows.net/$($ContainerName)/$($fileName)?$($SASToken.TrimStart('?'))"
            Method      = "GET"
            Headers     = @{
                'x-ms-blob-type' = "BlockBlob"
                'x-ms-meta-m1'   = 'v1'
                'x-ms-meta-m2'   = 'v2'
            }
            OutFile     = $filePath
            ErrorAction = 'Stop'
        }

        $null = Invoke-RestMethod @blobDownloadParams

        try {
            $model = Get-Content -Path $filePath | ConvertFrom-Json -ErrorAction Stop
        }
        finally {
            Remove-Item -LiteralPath $filePath -Force -Confirm:$false -ErrorAction SilentlyContinue
        }

    }
    else {
        Write-Error -Message "Parameter set $($PSCmdlet.ParameterSetName) has not been properly implemented." -ErrorAction Stop
    }

    Set-SCContext -Name $model.Name -RootAddressSpace $model.RootIPAddressRange -ConsumedIPRanges $model.ConsumedRanges
}

<#
.SYNOPSIS
 Export a PSSubnetCarver context to disk, or to Azure blob storage.
 
.DESCRIPTION
 Export a PSSubnetCarver context to a .json file, and either store it on the local disk, or in Azure blob storage. If in Azure blob storage, it will be uploaded via the REST API using a SAS token.
 
.PARAMETER Path
 The path of the .json file that will contain the stored information about the context.
 
.PARAMETER StorageAccountName
 The name of the Azure storage account.
 
.PARAMETER ContainerName
 The name of the container in the Azure storage account.
 
.PARAMETER SASToken
 The SAS token to use when making the REST request.
 
.PARAMETER ContextName
 The name of the context to export.
 
#>

function Export-SCContext {
    [CmdletBinding(DefaultParameterSetName = "ToFile")]
    Param(
        [Parameter(Mandatory = $true, Position = 0, ParameterSetName = "ToFile")]
        [string]$Path,

        [Parameter(Mandatory = $true, Position = 0, ParameterSetName = "ToAzure")]
        [string]$StorageAccountName,

        [Parameter(Mandatory = $true, Position = 1, ParameterSetName = "ToAzure")]
        [string]$ContainerName,

        [Parameter(Mandatory = $true, Position = 2, ParameterSetName = "ToAzure")]
        [string]$SASToken,

        [Parameter(Mandatory = $false, Position = 1, ParameterSetName = "ToFile")]
        [Parameter(Mandatory = $false, Position = 3, ParameterSetName = "ToAzure")]
        [string]$ContextName = "default",

        [Parameter(ParameterSetName = "ToFile")]
        [switch]$Force
    )

    $model = Get-SCContext -Name $ContextName -ErrorAction Stop

    $serialModel = [PSCustomObject]@{Name = $model.Name; RootIPAddressRange = $model.RootIPAddressRange.ToString(); ConsumedRanges = [System.Collections.ArrayList]@() }

    $model.ConsumedRanges | ForEach-Object -Process { $null = $serialModel.ConsumedRanges.Add($_.ToString()) }

    $json = $serialModel | ConvertTo-Json

    if ($PSCmdlet.ParameterSetName -eq "ToFile") {
        $json | Out-File -FilePath $Path -Force:$Force
    }
    elseif ($PSCmdlet.ParameterSetName -eq "ToAzure") {
        $fileName = "$($ContextName.ToLower()).json"

        $filePath = Join-Path -Path $env:TEMP -ChildPath $fileName -ErrorAction Stop

        $json | Out-File -FilePath $filePath -Force -ErrorAction Stop

        try {
            $blobUploadParams = @{
                URI         = "https://$($StorageAccountName).blob.core.windows.net/$($ContainerName)/$($fileName)?$($SASToken.TrimStart('?'))"
                Method      = "PUT"
                Headers     = @{
                    'x-ms-blob-type'                = "BlockBlob"
                    'x-ms-blob-content-disposition' = "attachment; filename=`"$($fileName)`""
                    'x-ms-meta-m1'                  = 'v1'
                    'x-ms-meta-m2'                  = 'v2'
                }
                InFile      = $filePath
                ErrorAction = 'Stop'
            }

            $null = Invoke-RestMethod @blobUploadParams
        }
        finally {
            Remove-Item -LiteralPath $filePath -Force -Confirm:$false -ErrorAction SilentlyContinue
        }
    }
    else {
        Write-Error -Message "Parameter set $($PSCmdlet.ParameterSetName) has not been properly implemented."
    }



}