# setup
$rootDrive = (get-location).Drive.Name + ":"
$pathDeployments = Join-Path -Path "$rootDrive" -ChildPath "Deployments"
$pathAppConfig = "$pathDeployments\UI\AAT.Genie.Simulator\1.0.0.0\AAT.Genie.DisplayState.exe.config"

function GetConfigValue ($key){
    # read the simulator config in xml
	[System.Xml.XmlDocument]$doc = new-object System.Xml.XmlDocument
	$doc.Load($pathAppConfig)

	foreach($item in $doc.get_DocumentElement().appSettings.add)
	{
		if($item.key -eq $key)
		{
            $value = $item.value
            if ($value -eq $null) { $value = "" }
            return $value
		}           
	}
}

# installation particulars
$machineName = GetConfigValue "MachineName"
if ($machineName.Length -eq 0) { $machineName = [System.Net.Dns]::GetHostName() }
$residentId = GetConfigValue "ResidentId"
$apiBaseUrl = GetConfigValue "ApiBaseUrl"
$isStage = $apiBaseUrl.IndexOf("-stage") -gt 0
if ($isStage) { $environment = "Stage" }
Else { $environment = "Production" }

Try {
    Write-Host -ForegroundColor green "`nInstalling AAT Genie Kiosk..."

    # environment
    Write-Host -ForegroundColor green "`nEnvironment: " -NoNewLine
    Write-Host -ForegroundColor yellow "$environment"

    # machine name
    Write-Host -ForegroundColor green "Machine Name: " -NoNewLine
    Write-Host -ForegroundColor yellow "$machineName"

    # resident id
    if ($residentId.Length -gt 0) 
    {
        Write-Host -ForegroundColor green "ResidentId: " -NoNewLine
        Write-Host -ForegroundColor yellow "$residentId"
    }
    Write-Host

    $installPath = "$pathDeployments\Install\PowerShell"
    
    invoke-expression -Command $installPath\CreateEventLogSources.ps1
    invoke-expression -Command $installPath\CreateMessageQueues.ps1
    invoke-expression -Command $installPath\CreateScheduledTasks.ps1
    invoke-expression -Command $installPath\CopyRedistributables.ps1
    invoke-expression -Command $installPath\Sync.ps1
    invoke-expression -Command $installPath\InstallServices.ps1

    # Disable the services that participate in auto updating Windows
    invoke-expression -Command "$installPath\AutoUpdateServices.ps1"

    Write-Host -ForegroundColor green "`nInstallation complete.`n"
}
Catch {
    Write-Host -ForegroundColor red $_.Exception.Message
    Write-Host -ForegroundColor yellow "`nInstallation aborted.`n"
    $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
}