Public/Tasks/Invoke-InstallPackageTask.ps1

Set-StrictMode -Version 2.0



Function Invoke-InstallPackageTask {
    [CmdletBinding(SupportsShouldProcess=$true)]
    param(
        [Parameter(Mandatory=$true)]
        [string]$Name,
        [Parameter(Mandatory=$true)]
        [string]$Package,
        [Parameter(Mandatory=$true)]
        [string]$PhysicalPath
    )

    Write-TaskInfo "Installing Package $Package" -Tag 'PackageInstall'

    #Generate a random 10 digit folder name. For security
    $folderKey = -join ((97..122) | Get-Random -Count 10 | % {[char]$_})

    #Generate a Access Key (hi there TDS)
    $accessKey = New-Guid

    Write-TaskInfo "Folder Key = $folderKey" -Tag 'PackageInstall'
    Write-TaskInfo "Access Guid = $accessKey" -Tag 'PackageInstall'

    $moduleRoot = Split-Path (Get-Module SifHelper).Path -parent
    $asmx = Join-Path -Path $moduleRoot -ChildPath 'Tools\PackageInstaller.asmx'
    $sourceAgentPath = Resolve-Path $asmx
    #The path to the source Agent. Should be in the same folder as I'm running
    # $sourceAgentPath = Resolve-Path "PackageInstaller.asmx"

    #The folder on the Server where the Sitecore PackageInstaller folder is to be created
    $packageInstallPath = [IO.Path]::Combine($PhysicalPath, 'sitecore', 'PackageInstaller')

    #The folder where the actuall install happens
    $destPath = [IO.Path]::Combine($PhysicalPath, 'sitecore', 'PackageInstaller', $folderKey)

    #Full path including the installer name
    $fullFileDestPath = Join-Path $destPath "PackageInstaller.asmx"

    Write-TaskInfo "Source Agent [$sourceAgentPath]" -Tag 'PackageInstall'
    Write-TaskInfo "Dest AgentPath [$destPath]" -Tag 'PackageInstall'

    #Forcibly cread the folder
    New-Item -ItemType Directory -Force -Path $destPath

    #Read contents of the file, and embed the security token
    (Get-Content $sourceAgentPath).replace('[TOKEN]', $accessKey) | Set-Content $fullFileDestPath

    #How do we get to Sitecore? This URL
    $webURI = UriBuilder -scheme http -hostName $Name -path "sitecore/PackageInstaller/$folderKey/packageinstaller.asmx" -query "WSDL"
    # $webURI = "$siteURL/sitecore/PackageInstaller/$folderKey/packageinstaller.asmx?WSDL"

    Write-TaskInfo "Url $webURI" -Tag 'PackageInstall'

    #Do the install here
    $proxy = New-WebServiceProxy -uri $webURI
    $proxy.Timeout = 1800000

    #Invoke our proxy
    $proxy.InstallZipPackage($Package, $accessKey)

    #Remove the folderKey
    Remove-Item $packageInstallPath -Recurse
}

Register-SitecoreInstallExtension -Command Invoke-InstallPackageTask -As InstallPackage -Type Task -Force