RDWebClientManagement.psm1

#
# Copyright (C) Microsoft. All rights reserved.
#

$defaultInstallationPath = $env:ProgramFiles + '\RemoteDesktopWeb'
$configKeyPath = 'HKLM:\Software\Microsoft\RemoteDesktopWeb'
$installedPathValueName = 'InstalledPath'
$managementToolsVersionName = 'ManagementToolsVersion'
$suppressTelemetryValueName = 'SuppressTelemetry'
$launchResourceInBrowserValueName = 'LaunchResourceInBrowser'
$internalDirName = 'Internal'
$clientDirName = 'Clients'
$packageTempDirName = 'Temp'
$configDataDirName = 'Config'
$prodClientVdirName = 'webclient'
$testClientVdirName = 'webclient-test'
$everybodyIdentity = New-Object System.Security.Principal.SecurityIdentifier 'S-1-1-0'
$everybodyReadRule = New-Object System.Security.AccessControl.FileSystemAccessRule $everybodyIdentity,'Read','Allow'
$nobodyReadRule = New-Object System.Security.AccessControl.FileSystemAccessRule $everybodyIdentity,'Read','Deny'
$rdWebPath = '/RDWeb'
$manifestFileName = 'manifest.json'
$clientContentDirName = 'content'

[System.Reflection.Assembly]::LoadWithPartialName('System.Security.Cryptography.X509Certificates')

function GetIISServerManager
{
    $iisServer = $null
    try
    {
        $iisServer = Get-IISServerManager
    }
    catch
    {
        Write-Error "The operation cannot be completed. RD Web Access does not appear to be installed on the system."
        return $null
    }

    return $iisServer
}

function UpdateIISContext
{
    [OutputType([Boolean])]
    [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='Low')]
    Param(
        [parameter(Mandatory=$true)]
        $iisContext
    )

    $iisContext.IISServerManager = GetIISServerManager
    if (!$iisContext.IISServerManager)
    {
        return $false
    }

    $webSites = Get-IISSite
    Foreach ($site in $webSites)
    {
        $rdWebApp = $site.Applications | Where-Object {$_.Path -eq $rdWebPath } | Select-Object -First 1
        if ($rdWebApp)
        {
            $iisContext.RdWebApplication = $rdWebApp
            $iisContext.RdWebSite = $site

            Break
        }        
    }

    if (!$iisContext.RdWebApplication)
    {
        Write-Error 'RD Web Access does not appear to be installed on the system.'
        return $false
    }
    else
    {
        $iisContext.ProdClientVdir = $iisContext.RdWebApplication.VirtualDirectories | Where-Object {$_.Path -eq "/$prodClientVdirName"} | Select-Object -First 1
        $iisContext.ProdClientConfigVdir = $iisContext.RdWebApplication.VirtualDirectories | Where-Object {$_.Path -eq "/$prodClientVdirName/config"} | Select-Object -First 1
        $iisContext.TestClientVdir = $iisContext.RdWebApplication.VirtualDirectories | Where-Object {$_.Path -eq "/$testClientVdirName"} | Select-Object -First 1
        $iisContext.TestClientConfigVdir = $iisContext.RdWebApplication.VirtualDirectories | Where-Object {$_.Path -eq "/$testClientVdirName/config"} | Select-Object -First 1
    }

    return $true
}

function EnsureDirectoryExists
    (
        [Parameter(mandatory=$true)]
        $Path,
        $AccessRule
    )
{
    $targetDir = Get-Item $Path -ErrorAction SilentlyContinue
    if (!$targetDir)
    {
        $targetDir = New-Item -Path $Path -ItemType 'directory'
        if (!$targetDir)
        {
            return $FALSE
        }

        if ($AccessRule)
        {
            $acl = Get-Acl $Path
            $acl.SetAccessRule($AccessRule)
            Set-Acl $Path $acl
        }
    }

    return $TRUE
}

function UpdateDeploymentSettingsFile
    (
    $context
    )
{
    $deploymentSettings = @{
        'deploymentType' = 'rdWeb';
        'suppressTelemetry' = $context.DeploymentSettings.SuppressTelemetry
        };

    $disableLaunchResourcesInBrowser = $context.ConfigKey.GetValue($launchResourceInBrowserValueName)
    if($disableLaunchResourcesInBrowser -ne $null) {
        $deploymentSettings.Add('launchResourceInBrowser', ($disableLaunchResourcesInBrowser -gt 0));
    }

    Set-Content -Path $context.DeploymentSettingsPath ('var DeploymentSettings = ' + (ConvertTo-Json $deploymentSettings))
}

function EnsureInitialized
{
    [OutputType([Boolean])]
    [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='Low')]
    Param(
        $context,
        [string] $installPath
    )

    if ($env:RdWebClientManagementCatalogURL)
    {
        $context.PackageCatalogUrl = $env:RdWebClientManagementCatalogURL
    }
    else
    {
        $context.PackageCatalogUrl = 'https://go.microsoft.com/fwlink/?linkid=2005418'
    }

    if (!$installPath)
    {
        $installPath = $defaultInstallationPath
    }
    $internalDirPath = Join-Path -Path $installPath -ChildPath $internalDirName
    $context.ClientPath = Join-Path -Path $internalDirPath -ChildPath $clientDirName
    $context.PackageTempPath = Join-Path -Path $internalDirPath -ChildPath $packageTempDirName
    $context.ConfigDataPath = Join-Path -Path $internalDirPath -ChildPath $configDataDirName
    $context.BrokerCertPath = Join-Path -Path $context.ConfigDataPath -ChildPath 'brokercert.cer'
    $context.DeploymentSettingsPath = Join-Path -Path $context.ConfigDataPath -ChildPath 'deploymentSettings.js'

    $installedDir = Get-Item $installPath -ErrorAction SilentlyContinue
    if (!$installedDir)
    {
        if (!$PSCmdlet.ShouldProcess(
            "RDWebClientManagement in '$installPath'",
            'Install'))
        {
            return $false
        }
    }

    $freshInstall = $FALSE
    if (!$context.ConfigKey)
    {
        $context.ConfigKey = New-Item -Path $configKeyPath
        $context.ConfigKey.SetValue($installedPathValueName, $installPath)
        $context.ConfigKey.SetValue($suppressTelemetryValueName, $false, [Microsoft.Win32.RegistryValueKind]::DWord)
        $context.InstalledPath = $installPath
        $freshInstall = $TRUE
    }

    $lastVersionStr = $context.ConfigKey.GetValue($managementToolsVersionName)
    if (!$lastVersionStr)
    {
        $lastVersionStr = '0.8'
    }
    $lastVersion = [System.Version]$lastVersionStr

    if (!$freshInstall -and ($lastVersion -lt [System.Version]'1.0'))
    {
        Write-Error ("The web client was installed using an older version of RDWebClientManagement and " +
        "must first be removed before deploying the new version. Using the old version of " +
        "RDWebClientManagement, uninstall the web client by running 'Uninstall-RDWebClient'. " +
        "Then reinstall the web client using this new module. For more information, " +
        "visit https://go.microsoft.com/fwlink/?linkid=870181 .")
        return $FALSE
    }

    $context.ConfigKey | Set-ItemProperty -Name $managementToolsVersionName -Value $context.Version.ToString()
    
    if (!$installedDir)
    {
        Write-Warning "Initializing RDWebClientManagement in '$installPath'. To uninstall, use Uninstall-RDWebClient."
        if (!(EnsureDirectoryExists -Path $installPath))
        {
            return $FALSE
        }
    }

    if (!(EnsureDirectoryExists -Path $internalDirPath -AccessRule $nobodyReadRule))
    {
        return $FALSE
    }

    if (!(EnsureDirectoryExists -Path $context.ClientPath -AccessRule $everybodyReadRule))
    {
        return $FALSE
    }

    if (!(EnsureDirectoryExists -Path $context.PackageTempPath))
    {
        return $FALSE
    }

    if (!(EnsureDirectoryExists -Path $context.ConfigDataPath -AccessRule $everybodyReadRule))
    {
        return $FALSE
    }
    
    $context.DeploymentSettings = @{
        'SuppressTelemetry' = $false;
        }

    $disableTelemetry = $context.ConfigKey.GetValue($suppressTelemetryValueName)
    $context.DeploymentSettings.SuppressTelemetry = ($null -ne $disableTelemetry) -and ($disableTelemetry -gt 0)

    $disableLaunchResourcesInBrowser = $context.ConfigKey.GetValue($launchResourceInBrowserValueName)
    if($disableLaunchResourcesInBrowser -ne $null) {
        $context.DeploymentSettings.Add('LaunchResourceInBrowser', ($disableLaunchResourcesInBrowser -gt 0));
    }

    UpdateDeploymentSettingsFile $context
        
    return $TRUE
}

function GetModuleContext
{
    $contextProps = @{};
    $contextProps.Version = (Get-Module RDWebClientManagement).Version
    $contextProps.ConfigKey = Get-Item $configKeyPath -ErrorAction SilentlyContinue
    [string]$contextProps.InstalledPath = $null
    [string]$contextProps.ClientPath = $null
    [string]$contextProps.PackageTempPath = $null
    [string]$contextProps.ConfigDataPath = $null
    [string]$contextProps.BrokerCertPath = $null
    [string]$contextProps.DeploymentSettingsPath = $null
    $contextProps.PackageCatalogUrl = $null
    $contextProps.DeploymentSettings = @{}


    if ($contextProps.ConfigKey)
    {
        $contextProps.InstalledPath = $contextProps.ConfigKey.GetValue($installedPathValueName)
    }

    $context = New-Object -TypeName PSObject -Property $contextProps

    return $context;
}

function GetModuleIISContext
{
    $contextProps = @{};

    $contextProps.IISServerManager = $null
    $contextProps.RdWebApplication = $null
    $contextProps.RdWebSite = $null

    [Microsoft.Web.Administration.VirtualDirectory]$contextProps.ProdClientVdir = $null
    [Microsoft.Web.Administration.VirtualDirectory]$contextProps.ProdClientConfigVdir = $null
    [Microsoft.Web.Administration.VirtualDirectory]$contextProps.TestClientVdir = $null
    [Microsoft.Web.Administration.VirtualDirectory]$contextProps.TestClientConfigVdir = $null

    $iisContext = New-Object -TypeName PSObject -Property $contextProps

    return $iisContext;
}

function CheckClientSupport
{
    Param(
        [Parameter(mandatory=$true)]
        $context,
        [Parameter(mandatory=$true)]
        $package
    )

    if (!$package.minRDWebClientManagementVersion -or ([System.Version]$package.minRDWebClientManagementVersion -gt $context.Version) )
    {
        Write-Error "The requested package cannot be installed with a version of RDWebClientManagement lower than '$($package.minRDWebClientManagementVersion)'."
        return $FALSE
    }

    return $TRUE
}

function GetRDWebClientPackagesInternal
{
    Param(
        [Parameter(mandatory=$true)]
        $context
    )

    foreach ($clientDir in Get-ChildItem $context.ClientPath -Directory)
    {
        $clientObject = $null
        $clientObject = Get-ChildItem $clientDir.FullName $manifestFileName -File | Get-Content -ErrorAction Continue | ConvertFrom-Json -ErrorAction Continue
        if ($clientObject -and $clientObject.version)
        {
            $clientObject | Add-Member 'path' $clientDir.FullName
            $clientObject | Add-Member '_baseVersion' ([System.Version]::Parse(($clientObject.version -replace '^([0-9.]*).*$','$1')))

            Write-Output $clientObject
        }
    }
}

<#
.SYNOPSIS
Entirely removes the Remote Desktop web client from the system, including any installed client packages and configured settings
#>

function Uninstall-RDWebClient
{
    [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='High')]Param()

    $context = GetModuleContext

    if (!$PSCmdlet.ShouldProcess(
        'The Remote Desktop web client, including any installed client packages and configured settings.',
        'Uninstall'
    ))
    {
        return
    }

    if ($context.InstalledPath)
    {
        $iis = [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.Web.Administration')
        if ($iis)
        {
            $iisContext = GetModuleIISContext
            if (!(UpdateIISContext $iisContext))
            {
                Write-Warning "Installed web client packages not found. Continuing with rest of uninstallation."
                $iisContext = $null
            }
        }
        else 
        {
            $iisContext = $null
        }

        if ($iisContext -and $iisContext.RdWebApplication -and $iisContext.IISServerManager)
        {
            $confChanged = $FALSE

            if ($iisContext.TestClientVdir)
            {
                $iisContext.RdWebApplication.VirtualDirectories.Remove($iisContext.TestClientVdir)
                $confChanged = $TRUE
            }

            if ($iisContext.TestClientConfigVdir)
            {
                $iisContext.RdWebApplication.VirtualDirectories.Remove($iisContext.TestClientConfigVdir)
                $confChanged = $TRUE
            }
                        
            if ($iisContext.ProdClientVdir)
            {
                $iisContext.RdWebApplication.VirtualDirectories.Remove($iisContext.ProdClientVdir)
                $confChanged = $TRUE
            }

            if ($iisContext.ProdClientConfigVdir)
            {
                $iisContext.RdWebApplication.VirtualDirectories.Remove($iisContext.ProdClientConfigVdir)
                $confChanged = $TRUE
            }

            if ($confChanged)
            {
                $iisContext.IISServerManager.CommitChanges()
            }
        }
        
        $internalPath = Join-Path $context.InstalledPath $internalDirName

        $acl = Get-Acl $internalPath
        $acl.RemoveAccessRule($nobodyReadRule) | Out-Null
        Set-Acl $internalPath $acl


        Get-Item $context.InstalledPath | Remove-Item -Recurse -Force
    }
    else
    {
        Write-Error 'The Remote Desktop web client is not installed.'
        return
    }

    Remove-Item $configKeyPath -ErrorAction SilentlyContinue
}

<#
.SYNOPSIS
Finds the Remote Desktop web client packages that are available for installation
 
.PARAMETER RequiredVersion
Specifies the exact version of the package to find. By default, Find-RDWebClientPackage only returns the newest available version.
 
.PARAMETER AllVersions
Indicates that Find-RDWebClientPackage should return all available versions of the client. By default, Find-RDWebClientPackage only returns the newest available version.
 
.EXAMPLE
Find-RDWebClientPackage
 
Description
-----------
Finds the client package with the highest version
 
.EXAMPLE
Find-RDWebClientPackage -AllVersions
 
Description
-----------
Finds all available client packages
 
.EXAMPLE
Find-RDWebClientPackage -RequiredVersion 0.7.0
 
Description
-----------
Finds the client package with version number 0.7.0, if it is available
#>

function Find-RDWebClientPackage
{
    [CmdletBinding(SupportsShouldProcess=$true)]
    [OutputType([PSCustomObject])]
    Param(
        [Parameter()]
        [string]$RequiredVersion,
        [switch]$AllVersions
    )

    $context = GetModuleContext
    if (!(EnsureInitialized $context))
    {
        return
    }

    $catalog = Invoke-RestMethod $context.PackageCatalogUrl
    if (!$catalog -or !$catalog.packages)
    {
        Write-Error 'The package catalog could not be read or was invalid.'
        return
    }
        
    $results = $catalog.packages
    if ($RequiredVersion)
    {
        $results = $results | Where-Object {$_.version -eq $RequiredVersion}
    }

    foreach ($client in $results)
    {
        if ($client.version)
        {
            $client | Add-Member '_baseVersion' ([System.Version]::Parse(($client.version -replace '^([0-9.]*).*$','$1')))
        }
    }

    $results = $results | Sort-Object packageId,_baseVersion -Descending 
        
    if (!$AllVersions)
    {
        $results = $results | Select-Object -First 1
    }

    $results 
}

<#
.SYNOPSIS
Installs a Remote Desktop web client package locally
 
.PARAMETER RequiredVersion
Specifies the exact version of the package to install. If you do not add this parameter, Install-RDWebClientPackage installs the highest available version of the client.
 
.PARAMETER Source
File path for the RD web client package to install. The Save-RDWebClientPackage command can be used to download the RD web client package.
 
.EXAMPLE
Install-RDWebClientPackage
 
Description
-----------
Installs the client package with the highest version
 
.EXAMPLE
Install-RDWebClientPackage -RequiredVersion 0.7.0
 
Description
-----------
Installs the client package with version number 0.7.0, if it is available
 
.EXAMPLE
Install-RDWebClientPackage -Source c:\rdwebclientpackages\1.0.0.zip
 
Description
-----------
Installs the client package located at c:\rdwebclientpackages\1.0.0.zip
 
#>

function Install-RDWebClientPackage
{
    [CmdletBinding(SupportsShouldProcess=$true)]
    Param(
        [Parameter()]
        [string]$RequiredVersion,
        [Parameter()]
        [string]$Source
    )

    $context = GetModuleContext
    $initialized = !!(EnsureInitialized $context)
    $continue = $PSCmdlet.ShouldProcess('The Remote Desktop web client package','Install')
    if (!($initialized -and $continue))
    {
        return
    }

    $iis = GetIISServerManager
    if (!$iis)
    {
        return
    }

    if ($Source)
    {
        $newClientPath = Join-Path -Path $context.ClientPath -ChildPath ([System.IO.Path]::GetRandomFileName())
        Expand-Archive $Source $newClientPath | Out-Null

        $newClientObject = Get-ChildItem $newClientPath $manifestFileName -File | Get-Content -ErrorAction Continue | ConvertFrom-Json -ErrorAction Continue
        if ($newClientObject -and $newClientObject.version)
        {
            if ($RequiredVersion -and $RequiredVersion -ne $newClientObject.version)
            {
                Write-Warning 'The requested Remote Desktop web client version was not found.'
                Remove-Item $newClientPath -Recurse -Force
                return
            }

            $clients = GetRDWebClientPackagesInternal($context)
            foreach ($client in $clients)
            {
                if ($client.version -eq $newClientObject.version -and $client.path -ne $newClientPath)
                {
                    Write-Warning 'The requested Remote Desktop web client is already installed.'
                    Remove-Item $newClientPath -Recurse -Force
                    return
                }
            }
        }
        else
        {
            Write-Warning 'The source Remote Desktop web client package is not valid.'
            Remove-Item $newClientPath -Recurse -Force
            return
        }
    }
    else
    {
        $packageObject = $null    
        if ($RequiredVersion)
        {
            $packageObject = Find-RDWebClientPackage -RequiredVersion $RequiredVersion
            if (!$packageObject)
            {
                Write-Error 'The requested Remote Desktop web client package is not available.'
                return
            }
        }
        else
        {
            $packageObject = Find-RDWebClientPackage
            if (!$packageObject)
            {
                Write-Error 'The Remote Desktop web client is not available for installation'
                return
            }
        }
        
        if (GetRDWebClientPackagesInternal $context | Where-Object {$_.version -eq $packageObject.version})
        {
            Write-Warning 'The requested Remote Desktop web client is already installed.'
            return
        }

        if (!(CheckClientSupport $context $packageObject))
        {
            return
        }

        $archiveFileName = Join-Path -Path $context.PackageTempPath -ChildPath ([System.IO.Path]::GetRandomFileName() + '.zip')
        $webclient = New-Object System.Net.WebClient
        $webclient.DownloadFile($packageObject.url, $archiveFileName);

        $newClientPath = Join-Path -Path $context.ClientPath -ChildPath ([System.IO.Path]::GetRandomFileName())
        Expand-Archive $archiveFileName $newClientPath | Out-Null
        Remove-Item $archiveFileName
    }
}

<#
.SYNOPSIS
Saves a Remote Desktop web client package locally for installing later on same or different machine.
 
.PARAMETER RequiredVersion
Specifies the exact version of the package to install. If you do not add this parameter, Save-RDWebClientPackage saves the highest available version of the client.
 
.PARAMETER Path
Folder path for saving the web client package
 
.EXAMPLE
 
Save-RDWebClientPackage c:\rdwebclientpackages
 
Description
-----------
Saves the client package with the highest version to c:\rdwebclientpackages
 
.EXAMPLE
Save-RDWebClientPackage c:\rdwebclientpackages -RequiredVersion 1.0.0
 
Description
-----------
Saves the client package with version number 1.0.0, if it is available, to c:\rdwebclientpackages directory
#>

function Save-RDWebClientPackage
{
    [CmdletBinding(SupportsShouldProcess=$true)]
    Param(
        [Parameter(mandatory=$true, Position=0)]
        [string] $Path,        
        [Parameter(mandatory=$false)]
        [string]$RequiredVersion
    )

    $context = GetModuleContext
    $initialized = !!(EnsureInitialized $context)
    $continue = $PSCmdlet.ShouldProcess('The Remote Desktop web client package','Save')
    if (!($initialized -and $continue))
    {
        return
    }

    $packageObject = $null
    if ($RequiredVersion)
    {
        $packageObject = Find-RDWebClientPackage -RequiredVersion $RequiredVersion
        if (!$packageObject)
        {
            Write-Error 'The requested Remote Desktop web client package is not available.'
            return
        }
    }
    else
    {
        $packageObject = Find-RDWebClientPackage
        if (!$packageObject)
        {
            Write-Error 'The Remote Desktop web client is not available'
            return
        }
    }
    
    $archiveFileName = Join-Path -Path $Path -ChildPath ('rdwebclient-' + $packageObject.version + '.zip')
    $webclient = New-Object System.Net.WebClient
    $webclient.DownloadFile($packageObject.url, $archiveFileName);

    Write-Information "RD web client package saved '$archiveFileName'."
}

<#
.SYNOPSIS
Returns a list of all Remote Desktop web client packages that have been installed locally
#>

function Get-RDWebClientPackage
{
    [CmdletBinding(SupportsShouldProcess=$true)]
    [OutputType([PSCustomObject])]
    Param()

    $context = GetModuleContext
    if (!(EnsureInitialized $context))
    {
        return
    }
    
    $result = @()
    $clients = GetRDWebClientPackagesInternal($context)
    if ($clients)
    {
        $iis = [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.Web.Administration')
        if (!$iis)
        {
            Write-Error "IIS must be installed to perform this operation"
            return
        }

        $iisContext = GetModuleIISContext
        if (!(UpdateIISContext $iisContext))
        {            
            return
        }
        
        foreach ($client in $clients)
        {
            $client | Add-Member 'publishedAs' @()
            $clientContent = Join-Path $client.path $clientContentDirName
            if ($iisContext.TestClientVdir -and $iisContext.TestClientVdir.PhysicalPath -eq $clientContent)
            {
                $client.publishedAs += 'Test'
            }

            if ($iisContext.ProdClientVdir -and $iisContext.ProdClientVdir.PhysicalPath -eq $clientContent)
            {
                $client.publishedAs += 'Production'
            }

            $result += $client
        }
        $result | Sort-Object packageId,_baseVersion -Descending
    }
    else
    {
        Write-Information 'No clients are installed.'
    }

}

<#
.SYNOPSIS
Uninstalls a Remote Desktop web client package from this system
 
.PARAMETER RequiredVersion
Specifies the exact version of the package to uninstall.
 
.EXAMPLE
Uninstall-RDWebClientPackage -RequiredVersion 0.7.0
 
Description
-----------
Uninstalls the client package with version number 0.7.0, if it is available
#>

function Uninstall-RDWebClientPackage
{
    [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='Medium')]
    Param(
        [Parameter(mandatory=$true)]
        [string]$RequiredVersion
    )

    $context = GetModuleContext
    $initialized = !!(EnsureInitialized $context)
    $continue = $PSCmdlet.ShouldProcess("The Remote Desktop web client package, version '$RequiredVersion'",'Uninstall')
    if (!($initialized -and $continue))
    {
        return
    }

    $iis = GetIISServerManager
    if (!$iis)
    {
        return
    }

    $package = Get-RDWebClientPackage | Where-Object {$_.version -eq $RequiredVersion} | Select-Object -First 1
    if (!$package)
    {
        Write-Error 'The requested client package is not installed.'
        return
    }

    if ($package.publishedAs.Count -gt 0)
    {
        Write-Error 'The requested client package has been published. You must unpublish it with Unpublish-RDWebClientPackage before you can uninstall it.'
        return
    }

    Get-Item $package.path | Remove-Item -Recurse -Force
}

<#
.SYNOPSIS
Publishes a Remote Desktop web client package through IIS
 
.PARAMETER Type
Indicates the type of deployment to publish as. The type must be either 'Test' or 'Production'.
 
If the type is 'Test', the client will be published in the "RDWeb/webclient-test" vdir.
 
If the type is 'Production', the client will be published in the "RDWeb/webclient" vdir.
 
.PARAMETER RequiredVersion
Specifies the exact version of the package to publish.
 
.PARAMETER Latest
Specifies that the installed web client package with the highest version should be published.
 
.EXAMPLE
Publish-RDWebClientPackage -Latest -Type Test
 
Description
-----------
Publishes the installed web client with the highest version number into the "RDWeb/webclient-test" vdir
 
.EXAMPLE
Publish-RDWebClientPackage -RequiredVersion 0.7.0 -Type Production
 
Description
-----------
Publishes the installed web client with version number 0.7.0 into the "RDWeb/webclient" vdir
#>

function Publish-RDWebClientPackage
{
    [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='Medium')]
    Param(
        [Parameter(mandatory=$true, Position=0)]
        [ValidateSet('Test', 'Production')]
        [string]$Type,
        [Parameter(mandatory=$true, ParameterSetName = 'RequiredVersion')]
        [string]$RequiredVersion,
        [Parameter(mandatory=$true, ParameterSetName = 'Latest')]
        [switch]$Latest
    )

    $context = GetModuleContext
    $initialized = !!(EnsureInitialized $context)
    $continue = $PSCmdlet.ShouldProcess('The Remote Desktop web client package','Publish alongside Remote Desktop Web Access')
    if (!($initialized -and $continue))
    {
        return
    }
     
    $iis = [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.Web.Administration')
    if (!$iis)
    {
        Write-Error "IIS must be installed to perform this operation"
        return
    }

    $iisContext = GetModuleIISContext
    if (!(UpdateIISContext $iisContext))
    {
        return
    }   

    if (!(Get-Item -Path $context.BrokerCertPath -ErrorAction SilentlyContinue))
    {
        Write-Error 'A broker certificate must be installed before publishing a client. Use Import-RDWebClientBrokerCert.'
        return
    }

    $targetClient = $null
    if ($Latest)
    {
        $targetClient = Get-RDWebClientPackage | Sort-Object -Property _baseVersion -Descending | Select-Object -First 1
    }
    elseif ($RequiredVersion)
    {
        $targetClient = Get-RDWebClientPackage | Where-Object {$_.version -eq $RequiredVersion} | Select-Object -First 1
    }

    $previouspackage = Get-RDWebClientPackage | Where-Object {$Type -in $_.publishedAs} | Select-Object -First 1

    if ($previouspackage)
    {
        if ($previouspackage.version -eq $targetClient.version)
        {
            Write-Warning 'The requested package has already been published for this client type.'
            return
        }

        Write-Warning "Replacing the previously published client package for client type '$Type' (version = $($previouspackage.version) ) with (version = $($targetClient.version) )..."
    }

    if (!$targetClient)
    {
        Write-Error 'The requested client package is not installed.'
        return
    }
        
    if (!(CheckClientSupport $context $targetClient))
    {
        return
    }

    Write-Warning 'Using the Remote Desktop web client with per-device licensing is not supported.'
    
    [Microsoft.Web.Administration.VirtualDirectory]$targetVdir = $null
    [Microsoft.Web.Administration.VirtualDirectory]$targetConfigVdir = $null
    $targetVdirName = $null
    $targetConfigVdirPath = $null
    if ($Type -eq 'Test')
    {
        $targetVdir = $iisContext.TestClientVdir
        $targetVdirName = $testClientVdirName
        $targetConfigVdir = $iisContext.TestClientConfigVdir
        $targetConfigVdirPath = "/$testClientVdirName/config"
    }
    else
    {
        $targetVdir = $iisContext.ProdClientVdir
        $targetVdirName = $prodClientVdirName
        $targetConfigVdir = $iisContext.ProdClientConfigVdir
        $targetConfigVdirPath = "/$prodClientVdirName/config"
    }

    $clientContentPath = Join-Path $targetClient.path $clientContentDirName
    if ($targetVdir)
    {
        $targetVdir.PhysicalPath = $clientContentPath
    }
    else
    {
        $targetVdir = $iisContext.RdWebApplication.VirtualDirectories.Add("/$targetVdirName", $clientContentPath) | Out-Null
    }

    if ($targetConfigVdir)
    {
        $targetConfigVdir.PhysicalPath = $context.ConfigDataPath
    }
    else
    {
        $targetConfigVdir = $iisContext.RdWebApplication.VirtualDirectories.Add($targetConfigVdirPath, $context.ConfigDataPath) | Out-Null
    }

    Set-WebConfigurationProperty -PSPath "IIS:\Sites\$($iisContext.RdWebSite)\RDWeb" -Location $targetVdirName -Filter 'system.webServer/httpRedirect' -Name '.' -Value @{enabled = 'false'}
    
    $iisContext.IISServerManager.CommitChanges()
    UpdateIISContext($iisContext) | Out-Null
}

<#
.SYNOPSIS
Unpublishes a previously-published Remote Desktop web client package
 
.PARAMETER Type
Indicates the type of deployment to unpublish. The type must be either 'Test' or 'Production'.
 
If the type is 'Test', the client in the "RDWeb/webclient-test" vdir will be unpublished.
 
If the type is 'Production', the client in the "RDWeb/webclient" vdir will be unpublished.
 
.EXAMPLE
Unpublish-RDWebClientPackage -Type Production
 
Description
-----------
Unpublishes the currently-published production client
#>

function Unpublish-RDWebClientPackage
{
    [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='Medium')]
    Param(
        [Parameter(mandatory=$true)]
        [ValidateSet('Test', 'Production')]
        [string]$Type
    )

    $isTest = $Type -eq 'Test'

    $context = GetModuleContext
    $initialized = !!(EnsureInitialized $context)
    
    $iis = [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.Web.Administration')
    if (!$iis)
    {
        Write-Error "IIS must be installed to perform this operation"
        return
    }

    $iisContext = GetModuleIISContext
    if (!(UpdateIISContext $iisContext))
    {
        return
    }   

    if ($isTest)
    {
        $vdirName = $testClientVdirName
    }
    else
    {
        $vdirName = $prodClientVdirName
    }
    $continue = $PSCmdlet.ShouldProcess("The Remote Desktop web client in '$vdirName'",'Unpublish')
    if (!($initialized -and $continue))
    {
        return
    }

    [Microsoft.Web.Administration.VirtualDirectory]$targetVdir = $null
    [Microsoft.Web.Administration.VirtualDirectory]$targetConfigVdir = $null
    if ($isTest)
    {
        $targetVdir = $iisContext.TestClientVdir
        $targetConfigVdir =$iisContext.TestClientConfigVdir
    }
    else
    {
        $targetVdir = $iisContext.ProdClientVdir
        $targetConfigVdir =$iisContext.ProdClientConfigVdir
    }

    if ($targetVdir)
    {
        $iisContext.RdWebApplication.VirtualDirectories.Remove($targetVdir)

        if ($targetConfigVdir)
        {
            $iisContext.RdWebApplication.VirtualDirectories.Remove($targetConfigVdir)
        }

        Remove-WebConfigurationLocation -PSPath "IIS:\Sites\$($iisContext.RdWebSite)\RDWeb" -Name $vdirName | Out-Null

        $iisContext.IISServerManager.CommitChanges()
    }
    else
    {
        Write-Error 'The requested client type is not published.'
    }
}

<#
.SYNOPSIS
Imports a broker certificate file for use with the Remote Desktop web client
 
.PARAMETER Path
File path for the certificate file to import
 
.PARAMETER Password
The password to use in opening the certificate file.
 
.PARAMETER PromptForPassword
Indicates that Import-RDWebClientBrokerCert should interactively prompt the user for
a password to use in opening the certificate file.
 
.EXAMPLE
Import-RDWebClientBrokerCert brokercert.cer
 
Description
-----------
Imports a certificate from a .cer file
 
.EXAMPLE
Import-RDWebClientBrokerCert brokercert.pfx -PromptForPassword
 
Description
-----------
Imports a certificate from a password-protected .pfx file. An interactive prompt will be used to
request the password that is needed to open the file.
#>

function Import-RDWebClientBrokerCert
{
    [CmdletBinding(SupportsShouldProcess=$true)]
    Param(
        [Parameter(mandatory=$true, Position=0)]
        [string] $Path,
        [Parameter(mandatory=$false, ParameterSetName = 'NoPrompt')]
        [SecureString] $Password,
        [Parameter(mandatory=$true, ParameterSetName = 'WithPrompt')]
        [switch] $PromptForPassword
    )

    $context = GetModuleContext
    $initialized = !!(EnsureInitialized $context)
    $continue = $PSCmdlet.ShouldProcess('The certificate that identifies the Remote Desktop Connection Broker',
        'Import')
    if (!($initialized -and $continue))
    {
        return
    }
    
    $iis = GetIISServerManager
    if (!$iis)
    {
        return
    }

    $certificateCreateArgs = @($Path)

    $password = $Password
    if ($PromptForPassword)
    {
        $password = Read-Host -Prompt 'Password' -AsSecureString
    }

    if ($password)
    {
        $certificateCreateArgs += $password
    }

    $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 $certificateCreateArgs
    if ($cert)
    {
        [System.IO.File]::WriteAllBytes($context.BrokerCertPath, $cert.RawData)
    }
}

<#
.SYNOPSIS
Returns information about the broker certificate that is being used by the Remote Desktop web client
#>

function Get-RDWebClientBrokerCert
{
    [CmdletBinding(SupportsShouldProcess=$true)]
    [OutputType([System.Security.Cryptography.X509Certificates.X509Certificate2])]
    Param()

    $context = GetModuleContext
    if (!(EnsureInitialized $context))
    {
        return
    }

    $iis = GetIISServerManager
    if (!$iis)
    {
        return
    }

    if (Get-Item $context.BrokerCertPath -ErrorAction SilentlyContinue)
    {
        New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 @($context.BrokerCertPath)
    }
    else
    {
        Write-Information 'A broker certificate is not installed.'
    }
}

<#
.SYNOPSIS
Removes the broker certificate that is being used by the Remote Desktop web client
#>

function Remove-RDWebClientBrokerCert
{
    [CmdletBinding(SupportsShouldProcess=$true)]Param()

    $context = GetModuleContext
    $initialized = !!(EnsureInitialized $context)
    $continue = $PSCmdlet.ShouldProcess('The certificate that identifies the Remote Desktop Connection Broker',
        'Remove')
    if (!($initialized -and $continue))
    {
        return
    }

    $iis = GetIISServerManager
    if (!$iis)
    {
        return
    }

    if (Get-Item $context.BrokerCertPath -ErrorAction SilentlyContinue)
    {
        Remove-Item $context.BrokerCertPath
    }
    else
    {
        Write-Information 'A broker certificate is not installed.'
    }
}

<#
.SYNOPSIS
Sets a deployment setting for the Remote Desktop web client
.PARAMETER Name
Specifies the name of the setting
.PARAMETER Value
The new value for the setting
.EXAMPLE
Set-RDWebClientDeploymentSetting SuppressTelemetry $true
 
Description
-----------
Disables telemetry gathering in the client
#>

function Set-RDWebClientDeploymentSetting
{
    [CmdletBinding(SupportsShouldProcess=$true)]
    Param(
        [Parameter(mandatory=$true)]
        [string] $Name,
        [Parameter(mandatory=$true)]
        $Value
    )

    $context = GetModuleContext
    if (!(EnsureInitialized $context))
    {
        return
    }

    $iis = GetIISServerManager
    if (!$iis)
    {
        return
    }

    switch ($Name)
    {
        'SuppressTelemetry' {
            if ($Value -is [Boolean])
            {
                New-ItemProperty -Path $configKeyPath -Name $suppressTelemetryValueName -Value $Value -PropertyType DWORD -Force | Out-Null
                $context.DeploymentSettings[$Name] = $Value
                UpdateDeploymentSettingsFile $context
            }
            else
            {
                Write-Error 'This setting requires a value of type [Boolean].'
            }
        }
        'LaunchResourceInBrowser' {
            if ($Value -is [Boolean])
            {
                New-ItemProperty -Path $configKeyPath -Name $launchResourceInBrowserValueName -Value $Value -PropertyType DWORD -Force | Out-Null
                $context.DeploymentSettings[$Name] = $Value
                UpdateDeploymentSettingsFile $context
            }
            else
            {
                Write-Error 'This setting requires a value of type [Boolean].'
            }
        }
        default { Write-Error "Setting '$Name' does not exist." }
    }
}

<#
.SYNOPSIS
Resets a deployment setting for the Remote Desktop web client to its default value
.PARAMETER Name
Specifies the name of the setting
.EXAMPLE
Reset-RDWebClientDeploymentSetting LaunchResourceInBrowser
 
Description
-----------
Allows the user to choose how to launch resources enumerated by the client
#>

function Reset-RDWebClientDeploymentSetting
{
    [CmdletBinding(SupportsShouldProcess=$true)]
    Param(
        [Parameter(mandatory=$true)]
        [string] $Name
    )

    $context = GetModuleContext
    if (!(EnsureInitialized $context))
    {
        return
    }

    $iis = GetIISServerManager
    if (!$iis)
    {
        return
    }

    switch ($Name)
    {
        'SuppressTelemetry' {
            New-ItemProperty -Path $configKeyPath -Name $suppressTelemetryValueName -Value $DefaultValue -PropertyType DWORD -Force | Out-Null
            $context.DeploymentSettings[$Name] = $false
            UpdateDeploymentSettingsFile $context
        }
        'LaunchResourceInBrowser' {
            if($context.ConfigKey.GetValue($launchResourceInBrowserValueName) -ne $null)
            {
                Remove-ItemProperty -Path $configKeyPath -Name $launchResourceInBrowserValueName
            }
            if ($context.DeploymentSettings[$Name] -ne $null) 
            {
                $context.DeploymentSettings.Remove($Name)
                UpdateDeploymentSettingsFile $context
            }
        }
        default { Write-Error "Setting '$Name' does not exist." }
    }
}

<#
.SYNOPSIS
Gets the deployment settings for the Remote Desktop web client
.PARAMETER Name
Specifies the name of the setting to retrieve
.EXAMPLE
Get-RDWebClientDeploymentSetting
 
Description
-----------
Gets all deployment settings
 
.EXAMPLE
Get-RDWebClientDeploymentSetting SuppressTelemetry
 
Description
-----------
Gets the SuppressTelemetry deployment setting
#>

function Get-RDWebClientDeploymentSetting
{
    [CmdletBinding(SupportsShouldProcess=$true)]
    [OutputType([System.Collections.DictionaryEntry])]
    Param(
        [string] $Name
    )

    $context = GetModuleContext
    if (!(EnsureInitialized $context))
    {
        return
    }

    $iis = GetIISServerManager
    if (!$iis)
    {
        return
    }

    if ($Name)
    {
        if ($context.DeploymentSettings.ContainsKey($Name))
        {
            @{$Name = $context.DeploymentSettings[$Name]}.GetEnumerator()
        }
        else
        {
            Write-Error "Setting '$Name' does not exist."
            return
        }
    }
    else
    {
        $context.DeploymentSettings.GetEnumerator()
    }
}

# SIG # Begin signature block
# MIIdjgYJKoZIhvcNAQcCoIIdfzCCHXsCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUTFxf9rTLUQN4PN9Tpc/RaMis
# dNqgghhqMIIE2jCCA8KgAwIBAgITMwAAAR+XYwozuYPXKwAAAAABHzANBgkqhkiG
# 9w0BAQUFADB3MQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4G
# A1UEBxMHUmVkbW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMSEw
# HwYDVQQDExhNaWNyb3NvZnQgVGltZS1TdGFtcCBQQ0EwHhcNMTgxMDI0MjEwNzM3
# WhcNMjAwMTEwMjEwNzM3WjCByjELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hp
# bmd0b24xEDAOBgNVBAcTB1JlZG1vbmQxHjAcBgNVBAoTFU1pY3Jvc29mdCBDb3Jw
# b3JhdGlvbjElMCMGA1UECxMcTWljcm9zb2Z0IEFtZXJpY2EgT3BlcmF0aW9uczEm
# MCQGA1UECxMdVGhhbGVzIFRTUyBFU046NDlCQy1FMzdBLTIzM0MxJTAjBgNVBAMT
# HE1pY3Jvc29mdCBUaW1lLVN0YW1wIFNlcnZpY2UwggEiMA0GCSqGSIb3DQEBAQUA
# A4IBDwAwggEKAoIBAQCppklVnT29zi13dODY0ejMsdoe7n2iCvC6QdH5FJkRYfy+
# cXoHBmpDgDF/65Kt9GMmu/K8HKAzjKHeG18rgRXQagLwIIH5yCRbXGwOfuHIu1dC
# 26o/CT22+YlR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