Install/OnPrem/XM/Scaled/Install-CM.ps1

. "$PSScriptRoot\..\..\..\InstallParams.ps1" -Force
. "$PSScriptRoot\..\..\Solr\SolrParams.ps1" -Force
Import-Module "$PSScriptRoot\..\..\..\..\SQL\SQL-Module.psm1" -Force
Import-Module "$PSScriptRoot\..\..\..\..\Common\SSL\SSL-Module.psm1" -Force
Import-Module "$PSScriptRoot\..\..\..\..\Common\WebAdministration-Module.psm1" -Force
Import-Module "$PSScriptRoot\..\..\Install-Module.psm1" -Force
$ErrorActionPreference = "Stop"

$prefix = $global:Configuration.prefix
$license = $global:Configuration.license
$sqlServer = $global:Configuration.sql.serverName
$sqlUser = $global:Configuration.sql.adminUsername
$sqlAdminPassword = $global:Configuration.sql.adminPassword
$sqlSitecorePassword = $global:Configuration.sql.sitecorePassword
$solrURL = $SolrServiceURL
$package = Get-ChildItem -Path "$SAFInstallPackageDir\*" -Include *cm.scwdp.zip*
$sifConfiguration = GetSIFConfiguration -Name "sitecore-XM1-cm.json" -PackageName $package -DefaultValue "$PSScriptRoot\sitecore-XM1-cm.json"

$serverCert = BuildSitecoreServerCertName -Prefix $prefix

$count = 1

foreach ($cm in $global:Configuration.sitecore) {
    $hostNames = $cm.hostNames
    $siteName = $hostNames[0]
    $installDir = $cm.installDir
   
    Write-Output "Testing installation of Sitecore CM$count..."
    if (TestURI -Uri "https://$siteName") {
        Write-Output "Sitecore CM$count has been installed before. Going forward..."
    }
    else {
        Write-Output "Install Sitecore CM$count started..."

        $dbs = @("Core", "Master", "Web", "ExperienceForms")
        DeleteDatabases -SqlServer $sqlServer -Prefix $prefix -Databases $dbs -Username $sqlUser -Password $sqlAdminPassword

        $sitecoreParams = @{
            Path              = $sifConfiguration
            Package           = $package.FullName
            LicenseFile       = $license
            SqlDbPrefix       = $prefix
            SqlServer         = $sqlServer
            SqlAdminUser      = $sqlUser
            SqlAdminPassword  = $sqlAdminPassword
            SqlCoreUser       = "$($prefix)_coreuser"
            SqlCorePassword   = $sqlSitecorePassword
            SqlMasterUser     = "$($prefix)_masteruser"
            SqlMasterPassword = $sqlSitecorePassword
            SqlWebUser        = "$($prefix)_webuser"
            SqlWebPassword    = $sqlSitecorePassword
            SqlFormsUser      = "$($prefix)_formsuser"
            SqlFormsPassword  = $sqlSitecorePassword
            SolrCorePrefix    = $prefix
            SolrUrl           = $solrURL
            Sitename          = $siteName
            SSLCert           = $serverCert
            InstallDirectory  = $installDir
        }
        Install-SitecoreConfiguration @sitecoreParams
        AddWebBindings -SiteName $siteName -HostNames $hostNames
        AddWebBindings -SiteName $siteName -HostNames $hostNames -SSLCert $serverCert
        Write-Output "Install Sitecore CM$count done."
    }

    $count = $count + 1


}