Install/OnPrem/Install-Prerequisites.ps1

Import-Module "$PSScriptRoot\..\..\Common\Utils-Module.psm1" -Force
Import-Module "$PSScriptRoot\..\..\Common\WebAdministration-Module.psm1" -Force
Import-Module "$PSScriptRoot\..\..\SQL\Sql-Module.psm1" -Force
$ErrorActionPreference = "Stop"

function IsLocalSolrInstallation {
    return ![string]::IsNullOrEmpty($global:Configuration.search.solr.install.hostName)
}

function NeedsSQL {
    return ![string]::IsNullOrEmpty($global:Configuration.sql.adminUsername)
}

function IsAllInOne {
    return ($global:Configuration.system.serverRole -eq "AllInOne")
}

function ConfigureDotNetFramework {
    if((IsLocalSolrInstallation) -and !(IsAllInOne)) {
        return
    }
    if (Get-ChildItem "HKLM:SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\" | Get-ItemPropertyValue -Name Release | ForEach-Object { $_ -ge 394802 }) {
        Write-Output ".Net Framework 4.6.2 or newer is already installed. Skipping install..."
    }
    else {
        if ($global:Offline -eq $false) {
            choco install dotnet4.6.2 --limitoutput
            RefreshEnvironment
            Write-Output "Install .Net Framework 4.6.2 done."
        }
        else {
            Write-Warning "SAF is running in offline mode. It assumes that you have installed .NET Framework 4.6.2 or newer manually!"
            Start-Sleep -s 5
        }
    }
}

function EnableWindowsFeatures {
    $windowsFeatures = @("IIS-WebServerRole", "IIS-WebServer", "IIS-CommonHttpFeatures", 
        "IIS-CommonHttpFeatures", "IIS-HttpErrors", "IIS-HttpRedirect", "IIS-ApplicationDevelopment",
        "IIS-NetFxExtensibility45", "IIS-HealthAndDiagnostics", "IIS-HttpLogging", "IIS-LoggingLibraries",
        "IIS-RequestMonitor", "IIS-HttpTracing", "IIS-Security", "IIS-RequestFiltering", "IIS-Performance", 
        "IIS-WebServerManagementTools", "IIS-IIS6ManagementCompatibility", "IIS-Metabase", "IIS-ManagementConsole",
        "IIS-BasicAuthentication", "IIS-WindowsAuthentication", "IIS-StaticContent", "IIS-DefaultDocument",
        "IIS-WebSockets", "IIS-ApplicationInit", "IIS-NetFxExtensibility45", "IIS-ISAPIExtensions",
        "IIS-ISAPIFilter", "IIS-HttpCompressionStatic", "IIS-ASPNET45")

    foreach ($feature in $windowsFeatures) {
        if ((Get-WindowsOptionalFeature -FeatureName $feature -Online).State -ne "Enabled") {
            Write-Output "Enabling $feature..."
            Enable-WindowsOptionalFeature -FeatureName $feature -Online -All | Out-Null
        }
    }
}

function EnableWindowsServerFeatures {
    $windowsServerFeatures = @("Web-Server", "Web-WebServer", "Web-Common-Http", "Web-Default-Doc",
        "Web-Http-Errors", "Web-Static-Content", "Web-Http-Redirect", "Web-Health", "Web-Http-Logging",
        "Web-Log-Libraries", "Web-Request-Monitor", "Web-Http-Tracing", "Web-Performance",
        "Web-Stat-Compression", "Web-Dyn-Compression", "Web-Security", "Web-Filtering",
        "Web-Basic-Auth", "Web-Basic-Auth", "Web-App-Dev", "Web-Net-Ext45", "Web-AppInit",
        "Web-Asp-Net45", "Web-ISAPI-Ext", "Web-ISAPI-Filter", "Web-Includes",
        "Web-WebSockets", "Web-Mgmt-Tools", "Web-Mgmt-Console")

    foreach ($feature in $windowsServerFeatures) {
        if (!(Get-WindowsFeature $feature).Installed) {
            Write-Output "Enabling $feature..."
            Install-WindowsFeature -Name $feature | Out-Null
        }
    }
}

function InitializeIIS {
    if((IsLocalSolrInstallation) -and !(IsAllInOne)) {
        return
    }
    $operatingSystem = (Get-WmiObject win32_operatingsystem).Caption
    Write-Output "Configuring IIS for Sitecore development..."
    if (($operatingSystem -like '*server*') -or ($operatingSystem -like '*Server*')) {
        EnableWindowsServerFeatures
    }
    else {
        EnableWindowsFeatures
    }
}

function InstallUrlRewrite {
    if((IsLocalSolrInstallation) -and !(IsAllInOne)) {
        return
    }
    if ($global:Offline -eq $false) {
        choco upgrade urlrewrite --limitoutput
        RefreshEnvironment
    }
    else {
        Write-Warning "SAF is running in offline mode. It assumes that you have installed IIS URL Rewrite latest version manually!"
        Start-Sleep -s 5
    }
}

function InstallWebDeploy {
    if((IsLocalSolrInstallation) -and !(IsAllInOne)) {
        return
    }
    if ($global:Offline -eq $false) {
        choco upgrade webdeploy --limitoutput
        RefreshEnvironment
    }
    else {
        Write-Warning "SAF is running in offline mode. It assumes that you have installed WebDeploy latest version manually!"
        Start-Sleep -s 5
    }
}

function InstallRedistributable {
    if((IsLocalSolrInstallation) -and !(IsAllInOne)) {
        return
    }
    if ($global:Offline -eq $false) {
        choco upgrade vcredist2015 --limitoutput
        RefreshEnvironment
    }
    else {
        Write-Warning "SAF is running in offline mode. It assumes that you have installed Microsoft Visual C++ Redistributable latest version manually!"
        Start-Sleep -s 5
    }
}

function InstallSqlServerDependencies {
    if((IsLocalSolrInstallation) -and !(IsAllInOne)) {
        return
    }
   
    if(NeedsSQL) {
        try {
            taskkill /F /IM Ssms.exe
        }
        catch {}
        if ($global:Offline -eq $false) {
            choco upgrade sql-server-management-studio --limitoutput
            RefreshEnvironment
        }
        else {
            Write-Warning "SAF is running in offline mode. It assumes that you have installed SSMS latest version manually!"
            Start-Sleep -s 5
        }

        $sqlServer = $global:Configuration.sql.serverName
        $username = $global:Configuration.sql.adminUsername
        $password = $global:Configuration.sql.adminPassword
        EnableContainedDatabaseAuth -SqlServer $sqlServer -Username $username -Password $password
    }
}

function InstallNSSM {
    if ($global:Offline -eq $false) {
        choco upgrade nssm -y --limitoutput
        RefreshEnvironment
    }
    else {
        Write-Warning "SAF is running in offline mode. It assumes that you have installed Non-Sucking Service Manager latest version manually!"
        Start-Sleep -s 5
    }
}

function InstallJRE {
    if(!(IsLocalSolrInstallation)) {
        return
    }
    choco upgrade jre8 -PackageParameters "/exclude:32" -y --limitoutput
    RefreshEnvironment
}

function ImportSIF {
    EnableIISAdministration
    $repositoryURL = "https://sitecore.myget.org/F/sc-powershell/api/v2"

    if ($global:Offline -eq $false) {
        $repositoryName = "SitecoreGallery"

        # Check to see whether that location is registered already
        $existing = Get-PSRepository -Name $repositoryName -ErrorAction Ignore
    
        # If not, register it
        if ($existing -eq $null) {
            Write-Output "Registering $repositoryName '$repositoryURL'..."
            Register-PSRepository -Name $repositoryName -SourceLocation $repositoryURL -InstallationPolicy Trusted
        }
        else {
            Write-Warning "$repositoryName '$repositoryURL' is already registered."
        }
    
        # Ensure Trusted, so that users are not prompted before installing modules from that source.
        Set-PSRepository -Name $repositoryName -InstallationPolicy Trusted
        LoadLatestPSModule -Name "SitecoreInstallFramework"
    }
    else {
        Write-Warning "SAF is running in offline mode. It assumes that you have installed SIF manually!"
        Start-Sleep -s 5
        Get-Module "SitecoreInstallFramework" | Remove-Module -Force 
        Import-Module "SitecoreInstallFramework"
    }
}

ConfigureDotNetFramework
InstallSqlServerDependencies
InitializeIIS
InstallUrlRewrite
InstallWebDeploy
InstallRedistributable
InstallNSSM
InstallJRE
ImportSIF