InstanceCreationPlugins/webapplication-plugin.psm1

#requires -version 4

function ModuleRoot
{
    $MyInvocation.ScriptName | Split-Path -Parent
}
$PrivPath = $(Join-Path $(ModuleRoot | Split-Path -Parent) "\Private")

<#
.SYNOPSIS
    Plugin for creating web applications as defined in the ISPSInstance.config
.DESCRIPTION
    This plugin only acts on nodes with the Name attribute of "WebApplication".
    This element is an instruction to create an application shortcut or a URL shortcut.
    The shortcut will be placed in the %progdata%\IntelliSearch\<InstanceName>\<ShortcutName> folder
    The target path should be expanded and the shortcut path would look something like this:
    C:\ProgramFiles\IntelliSearch\<packageName>\bin\someexecutablefile.exe -f C:\ProgramData\IntelliSearch\<InstanceName>\someconfigfile.exe.config
 
    Both the StartupArgument and ConfigurationFile parameters are optional, but the ConfigurationFile parameter will not be used unless the StartupArgument is specified.
    The {0} in the StartupArgument parameter is a placeholder for the configuration path.
 
    <!--This element is an instruction to create a regular IIS website.
    The web client should be copied to its own instance folder.
    The website root should be at the absolute path to the WebRoot element in the instance copy.
    -->
    <WebApplication
        Type="IIS"
        Classic="true"
        WebRoot="\WebClient">
        <!--This element lists all authentication settings that should be set by default on an IIS website
        If DisableUnspecified is set to true, all authentication methods are disabled except for the ones listed here-->
        <SecurityModes DisableUnspecified="false">
            <!--SecurityMode elements specify what modes of authentication should be enabled or disabled-->
            <SecurityMode
                Name="basicAuthentication"
                Enabled="true" />
            <SecurityMode
                Name="windowsAuthentication"
                Enabled="true" />
        </SecurityModes>
    </WebApplication>
 
.EXAMPLE
    $Splat = @{
        Node = <XML node>
        InstanceName = "WebClient"
        InstanceDirectory = "C:\ProgramData\IntelliSearch\MyInstance\"
        ComponentDirectory "C:\ProgramFiles\IntelliSearch\IntelliSearch.Server.IndexManager.4.0.2\"
    }
    shortcut.plugin @Splat
.PARAMETER Node
    The XML node currently being iterated over
.PARAMETER InstanceName
    A hashtable with arguments for the plugin.
.PARAMETER InstanceDirectory
    The root directory of the new instance
.PARAMETER ComponentDirectory
    The root directory of the installed component
.INPUTS
    System.String
.OUTPUTS
    None
#>

function webapplication-plugin
{
    param (
        # XML node from ISPSInstance.config
        [Parameter(
            Mandatory = $true,
            Position = 0,
            ValueFromPipelineByPropertyName = $true,
            HelpMessage = "XML node from ISPSInstance.config")]
        $Node,

        # The name representing the new instance
        [Parameter(
            Mandatory = $true,
            Position = 1,
            ValueFromPipelineByPropertyName = $true,
            HelpMessage = "Instance name")]
        [ValidateNotNullOrEmpty()]
        [string] $InstanceName,

        # Path to the directory of the new instance
        [Parameter(
            Mandatory = $true,
            Position = 2,
            ValueFromPipelineByPropertyName = $true,
            HelpMessage = "Path to the directory of the new instance")]
        [ValidateNotNullOrEmpty()]
        [ValidateScript( {
                if (Test-Path -Path $_)
                {
                    $true
                }
                else
                {
                    Throw [System.Management.Automation.ItemNotFoundException] "${_}"
                }
                if (Test-Path -Path $_ -PathType Container)
                {
                    $true
                }
                else
                {
                    Throw [System.Management.Automation.ValidationMetadataException] "The path '${_}' is not a directory."
                }
            })]
        [string] $InstanceDirectory,

        # Path to the component nuget package directory
        [Parameter(
            Mandatory = $true,
            Position = 3,
            ValueFromPipelineByPropertyName = $true,
            HelpMessage = "Path to the component nuget package directory")]
        [ValidateNotNullOrEmpty()]
        [ValidateScript( {
                if (Test-Path -Path $_)
                {
                    $true
                }
                else
                {
                    Throw [System.Management.Automation.ItemNotFoundException] "${_}"
                }
                if (Test-Path -Path $_ -PathType Container)
                {
                    $true
                }
                else
                {
                    Throw [System.Management.Automation.ValidationMetadataException] "The path '${_}' is not a directory."
                }
            })]
        [string] $ComponentDirectory
    )

    if ($Node.Name -ne "WebApplication")
    {
        Write-Debug "Node name was not WebApplication"
        return
    }

    if ($Node.Type -ne "IIS")
    {
        Write-Debug "Node type was not IIS"
        return
    }

    if ((Get-WebSite -Name $InstanceName) -ne $null)
    {
        Throw "A website already exists with the name $InstanceName"
    }

    # Create an app pool for the website so we don't overwrite an older pool
    $AppPool = CreateWebAppPool -Name $InstanceName -Classic:([System.convert]::ToBoolean($Node.Classic))
    $WebSite = New-WebSite -Name $InstanceName -PhysicalPath (Join-Path $InstanceDirectory $Node.WebRoot) -ApplicationPool $AppPool.Name

    # Splat to simplify changes to security modes
    $WebConfSplat = New-Object -TypeName System.Collections.Hashtable
    $WebConfSplat.Filter = "/system.webServer/security/authentication/*"
    $WebConfSplat.Name = "Enabled"
    $WebConfSplat.PSPath = "IIS:\"
    $WebConfSplat.Location = "{0}" -f $InstanceName

    # DisableUnspecified flag disables all security modes before applying the specified modes.
    if ($Node.SecurityModes.DisableUnspecified)
    {
        $AuthenticationTypes = Get-WebConfigurationProperty @WebConfSplat

        $WebConfSplat.ErrorAction = "SilentlyContinue"
        $WebConfSplat.Value = $False
        foreach ($AuthType in $AuthenticationTypes)
        {
            $WebConfSplat.Filter = $AuthType.ItemXPath
            Set-WebConfigurationProperty @WebConfSplat | Out-Null
        }
    }

    # We want to continue applying settings even if the node is no longer valid
    $WebConfSplat.ErrorAction = "SilentlyContinue"
    foreach ($SecurityMode in $Node.SelectNodes("//SecurityModes/*"))
    {
        $WebConfSplat.Filter = "/system.webServer/security/authentication/{0}" -f $SecurityMode.Mode
        $WebConfSplat.Value = $SecurityMode.Enabled

        Write-Verbose ("Setting security mode for {0}" -f $SecurityMode.Mode)
        Set-WebConfigurationProperty @WebConfSplat | Out-Null
    }

    # Return the website info
    $WebSite
}

function CreateWebAppPool ([string]$Name, [switch]$Classic)
{
    # Forcefully overwrite a pool if it already exists.
    $AppPool = New-WebAppPool -Name $Name -Force

    if ($Classic)
    {
        $AppPool.managedPipelineMode = "Classic"
    }

    # Set any changes done to the pool before returning
    $AppPool | Set-Item -PassThru
}