' ---------------------------------------------------------------------------------------------------
' This script is used to fully silently install RayVentory/RayManageSoft based on RayManageSoft 10.6:
' IIS 7.5, IIS 8.0, IIS 8.5 (IIS 7.0 support removed)
' SQL Server 2014/2016 Express
' RayVentory Administration Server
' RayVentory Portal
' Distribution Server
' Documentation
' ---------------------------------------------------------------------------------------------------
'
' Requires:
' ---------------------------------------------------------------------------------------------------
' OS: Windows Server 2008 R2, Windows Server 2012, Windows Server 20012 R2, Windows Server 2016
' .NET 3.5: http://www.microsoft.com/en-us/download/details.aspx?id=21
' .NET 4.7: https://www.microsoft.com/en-us/download/details.aspx?id=55167
' Requierd KB: https://support.microsoft.com/en-us/help/4020302/the-net-framework-4-7-installation-is-blocked-on-windows-7-windows-ser
' PowerShell: http://technet.microsoft.com/en-us/library/hh847837.aspx
' 
' On Windows Server 2012, Windows Server 2012 R2, Windows Server 2016 prerequisites will be installed 
' by this script
'
' ---------------------------------------------------------------------------------------------------
' ---------------------------------------------------------------------------------------------------
'
' Author E. Grosse Holling
' Copyright 2015 (c) Raynet GmbH
' ---------------------------------------------------------------------------------------------------
' Change Log:
' ---------------------------------------------------------------------------------------------------
' 20151224 2.50 EGH: RayVentory 10.5 incl. Oracle Fix, SQL 2014 Express SP1, Comparex DNA
' 20160119 2.51 EGH: SQL Server Install Fix, Install Sequence
' 20160616 2.52 AP:  Added 10.5.1 Sources, removed msp
' 20170203 2.60 EGH: Added SQL 2016 Express for x64 (SQL 2014 legacy support for x86)
'					 RayVentory Server 10.6.0 Installer 
'						incl. Hofix RMS-2144, RMS-2211, RMS-2212, RMS-962
'					 RayVentory Portal 10.6.0
'					 Java JRE 1.8.0.111
' 20170222 2.61 EGH: Setup Parameter improvement
'					 File length check
'					 RayVentory Hotfix RMS-2269, RMS-2277
'					 Compress Managed Device Packages
' 20170301 2.62 EGH: RayVentory Hofix RMS-936, RMS-2186, RMS-2276, RMS-2212_V2
'					 Refresh Package Import (nddlm)
' 20170327 2.63 EGH: RayVentory Hofix RMS-2310
'					 Remote SQL Installation and create procedure update
' 					 Inventory Plugin Scripts
'					 Disable License Counting
'					 IP Option for params.ini
'					 WRI RayVentory.2017-03-27.001
' 20170508 2.64 EGH: RayVentory Hofix 
'						RMS-2279, RMS-2283, RMS-2293_v2, RMS-2297_v2, RMS-2311, RMS-2327, RMS-2334
'					 Fix Missing RayVentory Portal Files
' 20170601 2.65 EGH: RayVentory Hofix 
'						RMS-2357
' 20170622 2.66 EGH: RayVentory Fix for SAM Account missing in Domain
'					 New Core.xml for Inventor Tracing
'					 Fix Upgrade SSMS for SQL 2014
'					 Upgrade SQL 2014 sources to SP2
' 20170709 2.67 EGH: ReplaceIPRegistry added / ReplaceIP fixed
'					 SSRS Refresh added (manual task required)
'					 New RWI Version
'					 RayVentory Hofix
'						RMS-2226 (Oracle)
'					 RemoteCommands.xml updated
'					 Update f_OracleInstances function
' 20170714 2.68 EGH: Powershell check, remove alternate Datastreams, Database fill modfied
'					 Nmap for open ports @localhost/IP-Adress/Computername
' 20170728 2.69 EGH: New Inventory Plugin for Windows/SQL Produkt Keys
'					 Switch from Nmap to MgsIPScan
'					 More Successcodes added for 2012R2 Patches
'					 Powershell ExecutionPolicy Unrestricted
' 20170731 2.70 EGH: Powershell ExecutionPolicy Bypass
'					 Microsoft Windows 2008 Legacy Support
'					 Custom Scan Extension for ProducKey, SQL
' 20170920 2.71 EGH: RayVentory Hotfix
'						RMS-2406 (Plink), RMS-2535 (Reporting Timeout 2h), RMS-2389, RMS-2390, RMS-2391, RMS-2393 (License counting), RMS-2425 (Outdate npl), RMS-292 (Managed Device 10.6.0.2851)
'					 Postinstallation Taskfix for Windows 2016
'					 Infrastructure Report Fix
'					 Add Hotfixes to 
' 20170929 2.72 EGH: Distrubtion Server Installer
'					 RayVentory Hotfix for Distribution Server
'						RMS-2406 (Plink), RMS-2144 (DS Package Windows 10), RMS-2212_v2 (Databaseimport), RMS-2283 (DNS), RMS-2310 (Remote Execution Placeholder), RMS-2334 (Tracing), RMS-2347 (Discovery), RMS-2665 (Interactive Service)
'					 RayVentory Hotfix for Administration Server
'						RMS-2279_v2 (GPOAPI), RMS-2516 (UpdateGPOPermissions), #8504 (Messaging System), RMS-2665 (Interactive Service)
'					 Fix LicenseCounting configuration
'					 Add Messaging (ActiveMQ), Managed Device option
'					 Change Setup Directory Structure
'					 Insert Reboot after Windows Patch
'					 Stop/Start Services before applying hotfixes
'					 Add IIS Protocol/Port Binding
'					 Quiet Reboot added to "RemoteCommands.xml"
'					 Remote Inventory Windows (RWI) Version 10.6.38.10
' 20171102 2.73 EGH: Default Role setting (#8504 Messaging System, 936)
'					 .Net 4.7 Installer and JRE Check
'					 New Reboot check, added RunOnce to continue after reboot
'					 New Windows Server 2016 Scheduled Task Fix
'					 RayVentory Hotfix for Administration Server
'						RMS-2632 (ndtrack for Ubuntu), RMS-2711 (ndtack not working on Debian)
'					 RayVentory Hotfix for Distribution Server
'						RMS-2632 (ndtrack for Ubuntu), RMS-2711 (ndtack not working on Debian)
'					 Disable AUTO_CLOSE on Application Database
' 20171110 2.74 EGH: MSI quiet level handling
'					 Setup Step handling changed
'					 Windows Server 2016 Scheduled Task Fix Script fixed
'					 Log Level extended
'					 RunOnce in User Level for older OS
'					 RayVentory Portal port mapping added (same port as Default Web Site), Default Root is Default Web Site
' 20171117 2.75 EGH: Log Parameter fixed (strSubLogFile)
'					 SSMS Upgrade fixed
'					 Next step for smooth reboot
'					 Custom sequence for installation procedure
' 20171208 2.76 EGH: RayVentory Hotfix RV-chf-01 (Cumulative hotfix for RayVentory with remote inventory)
' 20180703 2.77 SK:  Removed the usage agent feature from the DS MSI install syntax.
'
'
' ---------------------------------------------------------------------------------------------------
' Known Issues:
' ---------------------------------------------------------------------------------------------------
' 					 Special characters not supported by RV Installer
'					 Upgrade SQL Server (maybe fixed by reboot)
' ---------------------------------------------------------------------------------------------------
' Folder structure:
' Doc - Documentation
' Portal - RayVentory Portal Media
' Server - RMS installation media
' SQL Express - folder containing SQL Express media
' Utils - various components required for the installation
' ---------------------------------------------------------------------------------------------------
Option Explicit
Wscript.echo "Initiating Script"
' ---------------------------------------------------------------------------------------------------
' Constant declaration
' ---------------------------------------------------------------------------------------------------

Const HKCR = &H80000000 'HKEY_CLASSES_ROOT
Const HKCU = &H80000001 'HKEY_CURRENT_USER
Const HKLM = &H80000002 'HKEY_LOCAL_MACHINE
Const HKUS = &H80000003 'HKEY_USERS
Const HKCC = &H80000005 'HKEY_CURRENT_CONFIG

' ---------------------------------------------------------------------------------------------------
' Variable declaration
' ---------------------------------------------------------------------------------------------------
Dim TAB : TAB  = CHR( 9 )
Dim CRLF : CRLF = CHR( 13 ) & CHR( 10 )
Dim strDisplayMode		' Installation message mode
Dim strDisplayModeArray : strDisplayModeArray = Array("Standard", "Verbose", "Quiet")
Dim strUILevelMSI		' Default UI Level for MSI
Dim strMode 			' Install or upgrade mode
Dim strModeArray : strModeArray = Array("Install", "Upgrade", "Refresh")
Dim strStep				' Store Current Step
Dim strNextStep			' Store Next Step
Dim strStepArray		' Stores Installation Steps for Installation Type
Dim strType 			' Setup Type: RayVentory AS, RayManageSoft AS, RayVentory DS
Dim strTypeArray : strTypeArray = Array("AS_RV", "AS_RMS", "DS", "CUSTOM")
Dim strInstallDrive 	' Drive to install on
Dim strMGSDatabase		' RayVentory/RayManageSoft database
Dim strSVCAccountName 	' Stores Service Account Name
Dim strSVCAccountPwd 	' Stores Service Account Password
Dim strSVCLogonDomain	' Stores Logon Type, 'local' default, Domainname for Domain users only !
Dim strReplaceIP		' Replace Hostname with IP Adress or value
Dim strSQLInstallMode 	' SQLExpress on the same server /or/ SQL for separately DB server installation - will be read by the "params.ini"
Dim strSQLInstallModeArray : strSQLInstallModeArray = Array("Install", "Upgrade", "SSMS", "None")
Dim strSQLServerName 	' SQL Server Name - will be read by the "params.ini"
Dim strSQLInstanceName 	' Stores SQL instance name (SQLExpress or ManageSoft) - will be read by the "params.ini"
Dim strSQLServerPort	' Stores SQL ServerPort
Dim strSQLFullInstanceName	' Stores Full SQL instance name (Servername\Instancename)
Dim	strSQLServerAuth	' SQL Server Auth
Dim strSQLServerAuthArray : strSQLServerAuthArray = Array("WindowsNT", "SQLServer")
Dim strSQLServerUser 	' SQL User - will be read by the "params.ini"
Dim strSQLServerPass 	' SQL Password - will be read by the "params.ini"
Dim strSSRSserverURL	' SQL Server Reporting Services (SSRS) Server URL
Dim strSSRSServerUser	' SSRS User - will be read by the "params.ini"
Dim strSSRSServerPass	' SSRS Password - will be read by the "params.ini"
Dim strSQLCollation		' Store SQL Collation if Set (Params.ini SQLCollation)
Dim strPortalInstall	' Install RayVentory Portal
Dim strPortalInstallArray : strPortalInstallArray = Array("True", "False")
Dim strInstallDNA		' Install Comparex DNA
Dim strInstallDNAArray : strInstallDNAArray = Array("True", "False")
Dim strDNADatabase		' DNA DATABASE
Dim strLogFile 		' Stores Log file name
Dim strLogFolder 		' Stores Log folder path
Dim strSubLogFile 		' Stores Log file name for current Sub/Function
Dim strIniFile 		' Stores INI file name
Dim strOSArch 		' Stores Architecture ("32-bit" or "64-bit")
Dim strOSVersion 	' Stores Windows Version
Dim strOSCaption 	' Stores OS name
Dim strOSServicePack ' Stores Major Service Pack Version
Dim strOS 		' Stores resulting Windows version (Win2008_32, Win2008_64, Win2008R2, Win2012, Win2012R2, Win2016)
Dim strOSPath	' Stores Windows Directory
Dim strIP 		' Stores local IP address
Dim strComputer 	' Stores Computer Name
Dim strInstallPath 	' Stores the path where RayVentory/RayManageSoft will be installed
Dim strPath 		' Stores path where this script is located
Dim strSQLAdminGroup 	' Stores SQL admin group
Dim strAdministrators 	' Stores local Administrators name
Dim strAdministratorsCaption 	' Stores local Administrators Caption
Dim strSystemName 	' Stores Name of the NT\AUTHORITY SYSTEM
Dim strProcess 		' Process to execute
Dim strParam 		' Process parameters
Dim strFolder			' Process working folder
Dim strWarehousePath 	' Path to the Warehouse folder
Dim strODBCToolsPath	' SQL ODBC Tools
Dim strSQLToolsPath		' SQL Tools
Dim strSQLToolsPath32	' SQL Tools (32 Bit)
Dim strScriptVersion	' Script Version
Dim strDefaultPath		' Parameter to set Default Path for fallback
Dim strIISVersionPath	' IIS config path by Version and OS 
Dim strSQLVersionPath	' SQL install Path by Version and OS
Dim strSSMSVersionPath	' SSMS install Path by Version and OS
Dim strOSSXSPath		' Path OS SXS Sources
Dim strErrorCode		' Errorcode Variable
Dim strLicenseCounting	' Enable/Disable License Counting
Dim strLicenseCountingArray : strLicenseCountingArray = Array("True", "False")
Dim strPowerShell1		' Powershell Version 1 installed
Dim strPowerShell3		' Powershell Version 3 installed
Dim strHotFixesID		' Required Hotfix Operating System
Dim strHotFixPath		' Path to Hotfix Repository for Operating System
Dim strImportParent		' Webresolver Parent
Dim strImportParentSQL	' Webresolver Parent SQL
Dim strImportUser		' ResolverImportUser for Database
Dim strImportPass		' ResolverImportPass for Database
Dim strImportTypes		' Preconfig ImportTypes
Dim strJobParent		' Hostname of the parnet Distribution Server
Dim strJobProtocol 		'Protocol used to poll Jobs
Dim strJobProtocolArray : strJobProtocolArray = Array("http", "https")
Dim strCustomMST 		' Customer Specific MST File
Dim strActiveMQ			' Enable/Disable ActiveMQ
Dim strActiveMQArray : strActiveMQArray = Array("True", "False")
Dim strInstallMD		' Enable/Disable Managed Device for Distribution Server
Dim strInstallMDArray : strInstallMDArray = Array("True", "False")
Dim strIISProtocol		' Set Protocol for IIS Default Web Site Binding
Dim strIISPort			' Set Port for IIS Default Web Site Binding
Dim strProgramData		' Get Path to programdata
Dim strRebootRequired : strRebootRequired = 0 ' Reboot Flag
' ---------------------------------------------------------------------------------------------------
strScriptVersion = "2.76"
Wscript.echo "Version : " & TAB & strScriptVersion
' ---------------------------------------------------------------------------------------------------
' Parameter Setup
' ---------------------------------------------------------------------------------------------------

'Make sure we are running elevated, prompt if not
Wscript.echo "Is elevated : " & TAB & isElevated
If Not isElevated Then getUacPrompt(getArguments())

' Declarations of the working directory
strPath = Replace(WScript.ScriptFullName, "Utils\" & WScript.ScriptName, "")
strDefaultPath = strPath
strIniFile = strPath & "params.ini"
strLogFolder = strPath & "Log"
strLogFile = strLogFolder & "\Setup.log"

' Get OS Configuration
Wscript.echo "Determining parameters"
Wscript.echo "This may take a few minutes..."

strComputer = GetEnvVariable("COMPUTERNAME")
strOSArch = GetWMIProperty(strComputer, "Win32_OperatingSystem", "OSArchitecture")
strOSVersion = GetWMIProperty(strComputer, "Win32_OperatingSystem", "Version")
strOSCaption = GetWMIProperty(strComputer, "Win32_OperatingSystem", "Caption")
strOSServicePack = GetWMIProperty(strComputer, "Win32_OperatingSystem", "ServicePackMajorVersion")
strOS = getOSName(strOSCaption, strOSVersion, strOSArch)
strOSPath = GetEnvVariable ("windir")
strProgramData = GetEnvVariable ("ProgramData")
strIP = GetIPAddress(strComputer)
strAdministrators = GetLocalGroupName("S-1-5-32-544")
strAdministratorsCaption = GetLocalGroupCaption("S-1-5-32-544")
strSystemName = GetLocalUserName ("S-1-5-18")

' Get Params.ini settings and set default if parameter missing

' [Common]
strType = isValueInScope(ReadIni(strIniFile,"Common","InstallType", true), strTypeArray, "as_rv")
strDisplayMode = isValueInScope(ReadIni (strIniFile,"Common","DisplayMode", true), strDisplayModeArray, "standard")
strMode = isValueInScope(ReadIni(strIniFile,"Common","InstallMode", true), strModeArray, "install")
strInstallDrive = Left(ReadIni(strIniFile,"Common","InstallDrive", false),1)
strIISProtocol = ReadIni(strIniFile,"Common","IISProtocol", true)
strIISPort = ReadIni(strIniFile,"Common","IISPort", true)
strCustomMST = ReadIni(strIniFile,"Common","CustomMST", true)
'If isBlank(strInstallDrive) Then strInstallDrive = "C"


If isBlank(strDisplayMode) Then	strDisplayMode = "standard"

If strDisplayMode = "quiet" _
Then 
	LogEvent "Going quiet from now on..."
	strUILevelMSI="/qn"
Else
	strUILevelMSI="/qb-"
End If


If isBlank(strIISProtocol) Then strIISProtocol = "http"
If isBlank(strIISPort) Then strIISPort = "80"

' [RVOptions]
strActiveMQ = isValueInScope(ReadIni(strIniFile,"RVOptions","ActiveMQ", true), strActiveMQArray, "false")

' User/Database/LicenseCounting required only for Administration Server
If strType = "as_rv" _
Or strType = "as_rms" _
Or strType = "custom" _
Then
	strLicenseCounting = isValueInScope(ReadIni(strIniFile,"RVOptions","LicenseCounting", true), strLicenseCountingArray, "false")
	strMGSDatabase = ReadIni(strIniFile,"RVOptions","MGSDatabase", false)
	strSVCAccountName = ReadIni(strIniFile,"RVOptions","SVCAccountName", false)
	strSVCAccountPwd = ReadIni(strIniFile,"RVOptions","SVCAccountPwd", false)
	strSVCLogonDomain = ReadIni(strIniFile,"RVOptions","SVCLogonDomain", false)
	If isBlank(strSVCAccountName) Then strSVCAccountName = "mgsuser"
	If isBlank(strSVCLogonDomain) Then strSVCLogonDomain = "local"
End If
strReplaceIP = lcase(ReadIni(strIniFile,"RVOptions","ReplaceIP", true))
If strReplaceIP <> "true" And strReplaceIP <> "false" Then strIP = strReplaceIP

' [SQL]
' SQL required only for Administration Server
If strType = "as_rv" _
Or strType = "as_rms" _
Or strType = "custom" _
Then
	strSQLAdminGroup = strAdministrators
	strSQLInstallMode = isValueInScope(ReadIni(strIniFile,"SQL","SQLInstallMode", true), strSQLInstallModeArray, strMode)
	strSQLCollation = ReadIni(strIniFile,"SQL","SQLCollation", true)
	strSQLServerName = lcase(ReadIni(strIniFile,"SQL","SQLServerName", true))
	strSQLInstanceName = ReadIni(strIniFile,"SQL","SQLInstanceName", true)
	strSQLServerAuth = isValueInScope(ReadIni(strIniFile,"SQL","SQLServerAuth", true), strSQLServerAuthArray, "WindowsNT")
	strSQLServerAuth = ReadIni (strIniFile,"SQL","SQLServerAuth", true)
	strSQLServerPort = ReadIni(strIniFile,"SQL","SQLServerPort", true)
	strSQLServerUser = ReadIni (strIniFile,"SQL","SQLServerUser", true)
	strSQLServerPass = ReadIni (strIniFile,"SQL","SQLServerPass", true)
	strSSRSServerUser = ReadIni (strIniFile,"SQL","SSRSServerUser", true)
	strSSRSServerPass = ReadIni (strIniFile,"SQL","SSRSServerPass", true)
	strSSRSserverURL = ReadIni (strIniFile,"SQL","SSRSserverURL", true)
	If isBlank(strSQLServerName) Then strSQLServerName = strComputer
	'If isBlank(strSQLInstanceName) Then strSQLInstanceName = "SQLExpress"
	If isBlank(strSSRSserverURL) Then strSSRSserverURL = SetSSRSserverURL(strSQLInstallMode)
	
	' Fill up SQL Parameter
	strSQLFullInstanceName = SetSQLInstanceName(strSQLInstallMode)
	If isBlank(strMGSDatabase) Then	strMGSDatabase = "ManageSoft"
	If isBlank(strSQLServerUser) Then strSQLServerUser = ""
	If isBlank(strSQLServerPass) Then strSQLServerPass = ""
End If

' [DS]
If strType = "ds" _
Or strType = "custom" _
Then
	strInstallMD = isValueInScope(ReadIni(strIniFile,"DS","InstallMD", true), strInstallMDArray, "true")
	strImportParent = ReadIni(strIniFile,"DS","ResolverParent", true)
	strImportParentSQL = ReadIni(strIniFile,"DS","ResolverParentSQL", true)
	strImportUser = ReadIni(strIniFile,"DS","ResolverImportUser", true)
	strImportPass = ReadIni(strIniFile,"DS","ResolverImportPass", true)
	strImportTypes = ReadIni(strIniFile,"DS","ResolverImportTypes", true)
	strJobParent = ReadIni(strIniFile,"DS","JobParent", true)
	strJobProtocol = isValueInScope(ReadIni(strIniFile,"DS","JobProtocol", true), strJobProtocolArray, "http")
	If isBlank(strImportParentSQL) Then strImportParentSQL = strImportParent
End If

' [Portal]
strPortalInstall = isValueInScope(ReadIni(strIniFile,"Portal","Install", true), strPortalInstallArray, "true")

' [DNA]
strInstallDNA = isValueInScope(ReadIni(strIniFile,"DNA","Install", true), strPortalInstallArray, "false")
strDNADatabase = ReadIni(strIniFile,"DNA","Database", true)
If isBlank(strDNADatabase) Then strDNADatabase = strMGSDatabase


' Set OS related configuration

' No OS Found
If isBlank(getOSVersion(strOSVersion)) Then
	LogEvent "Unsupported Operating System. Exiting..."
	ScriptQuit 1


' Microsoft Windows Server 2008
ElseIf getOSVersion(strOSVersion) = "6.0" Then

	If strOSServicePack < 2 Then
		LogEvent "Unsupported Service Pack level " & strOSServicePack
		LogEvent "Minimum requirement Service Pack 2.0"
		LogEvent "Exiting..."
		ScriptQuit 1
	End If
	
	strIISVersionPath = "LegacyIIS7"
	
	If strType = "as_rv" _
	Or strType = "as_rms" _
	Or strType = "custom" _
	Then
		If strOSArch = "32-Bit" Then
			strSQLVersionPath = strPath & "SQL Express\2014\SQLEXPRADV_x86_ENU.exe"
		Else
			strSQLVersionPath = strPath & "SQL Express\2014\SQLEXPRADV_x64_ENU.exe"
		End If
	End If

	strHotFixesID = Array ("968930")
	strHotFixPath = strPath & "Utils\Sources\kb\2008\Windows6.0-KB"	

' Microsoft Windows Server 2008 R2
ElseIf getOSVersion(strOSVersion) = "6.1" Then

	strIISVersionPath = "Utils\Config\config2008r2.xml"
	strHotFixesID = Array ("2813430","4019990")	
	strHotFixPath = strPath & "Utils\Sources\kb\2008R2\Windows6.1-KB"
	
	If strType = "as_rv" _
	Or strType = "as_rms" _
	Or strType = "custom" _
	Then
		If strOSArch = "32-Bit" Then
			strSQLVersionPath = strPath & "SQL Express\2014\SQLEXPRADV_x86_ENU.exe"
		Else
			strSQLVersionPath = strPath & "SQL Express\2014\SQLEXPRADV_x64_ENU.exe"
		End If
	End If

' Microsoft Windows Server 2012
ElseIf getOSVersion(strOSVersion) = "6.2" Then
	
	strIISVersionPath = strPath & "Utils\Config\\config2012.xml"
	strOSSXSPath = strPath & "Utils\Sources\sxs\2012.7z"
	strHotFixPath = strPath & "Utils\Sources\kb\2012\Windows8-RT-KB"
	strHotFixesID = Array ("4019990")	
	
	If strType = "as_rv" _
	Or strType = "as_rms" _
	Or strType = "custom" _
	Then
		strSQLVersionPath = strPath & "SQL Express\2016\SQLEXPRADV_x64_ENU.exe"
		strSSMSVersionPath = "SQL Express\2016\SSMS-Setup-ENU.exe"
	End If

' Microsoft Windows Server 2012 R2	
ElseIf getOSVersion(strOSVersion) = "6.3" Then
	
	strIISVersionPath = strPath & "Utils\Config\config2012R2.xml"
	strOSSXSPath = strPath & "Utils\Sources\sxs\2012R2.7z"
	strHotFixPath = strPath & "Utils\Sources\kb\2012R2\Windows8.1-KB"
	strHotFixesID = Array ("2919442", "2919355")
	
	If strType = "as_rv" _
	Or strType = "as_rms" _
	Or strType = "custom" _
	Then
		strSQLVersionPath = strPath & "SQL Express\2016\SQLEXPRADV_x64_ENU.exe"
		strSSMSVersionPath = "SQL Express\2016\SSMS-Setup-ENU.exe"
	End If

' Microsoft Windows Server 2016
ElseIf getOSVersion(strOSVersion) = "10.0" Then

	strIISVersionPath = strPath & "Utils\Config\config2016.xml"
	strOSSXSPath = strPath & "Utils\Sources\sxs\2016.7z"
	
	If strType = "as_rv" _
	Or strType = "as_rms" _
	Or strType = "custom" _
	Then
		strSQLVersionPath = strPath & "SQL Express\2016\SQLEXPRADV_x64_ENU.exe"
		strSSMSVersionPath = "SQL Express\2016\SSMS-Setup-ENU.exe"
	End If
	
Else
	LogEvent "Unsupported Operating System " &  strOSCaption & " (" & getOSVersion(strOSVersion) & "). Exiting..."
	ScriptQuit 1
	
End If

LogEvent "----------------------------------------------------------"
LogEvent "Setup config for " & strOSCaption

' Get Install directory from existing Installation
strInstallPath = getEtapInstallDir()
strWarehousePath = getWarehouse()

If strMode = "upgrade" Or strMode = "refresh" Then
	If isBlank(strInstallPath) Then
		LogEvent "Cannot find install path, " & strMode & " failed."
		LogEvent "Installation required!"
		LogEvent "Exiting..."
		ScriptQuit 1
	ElseIf isBlank(strWarehousePath) Then
		LogEvent "Cannot find warehouse path, " & strMode & " failed."
		LogEvent "Installation required!"
		LogEvent "Exiting..."
		ScriptQuit 1		
	End If
End If



' Set Install Path
If isBlank(strInstallPath) Then
	strInstallPath = ReadIni(strIniFile,"Common","InstallPath", true) 
	If isBlank(strInstallPath) Then strInstallPath = "RayVentory"
	
	' Set Warehouse Path
	If isBlank(strWarehousePath) Then 
		strWarehousePath = "C:\" & strInstallPath
		
		'Overwrite Path if drive is set
		If Len(strInstallDrive) = 1 Then 
			strWarehousePath = Replace(strWarehousePath, "C:", strInstallDrive & ":") 
		End If
	End If

	If strOSArch = "32-bit" Then
		strInstallPath = GetEnvVariable ("ProgramFiles") & "\" & strInstallPath
	Else
		strInstallPath = GetEnvVariable ("ProgramFiles(x86)") & "\" & strInstallPath
	End If
	
	'Overwrite Path if drive is set
	If Len(strInstallDrive) = 1 Then
		strInstallPath = Replace(strInstallPath, "C:", strInstallDrive & ":")
	End If
	
End If

' Preconfigure Installation Steps
If strType = "as_rv" _
Then 

	If strMode = "install" _ 
	Then
		strStepArray = Array("IS_CheckUpdates", "IS_InstallNET", "IS_InstallIIS", "IS_InstallJRE", "IS_CreateServiceAccount", "IS_InstallSQL", "IS_InstallSSMS", "IS_CreateSQLDB", "IS_CreateSQLUser", "IS_FillDatabase", "IS_InstallRV", "IS_ReplaceIPRegistry", "IS_ReplaceIPHierarchy", "IS_PostIIS", "IS_PostIISAS", "IS_Addons", "IS_PostSSRS", "IS_InstallPortal", "IS_InstallDNA", "IS_InstallOWC", "IS_PostInstall")
	ElseIf strMode = "upgrade" _
	Then
		strStepArray = Array("IS_CheckUpdates", "IS_InstallNET", "IS_InstallIIS", "IS_InstallJRE", "IS_InstallSQL", "IS_InstallSSMS", "IS_DatabaseMigration", "IS_FillDatabase", "IS_InstallPrePatch", "IS_UpgradeRV", "IS_ReplaceIPRegistry", "IS_ReplaceIPHierarchy", "IS_PostIIS", "IS_PostIISAS", "IS_Addons", "IS_PostSSRS", "IS_InstallPortal", "IS_InstallDNA", "IS_InstallOWC", "IS_PostInstall")
	ElseIf strMode = "refresh" _
	Then
		strStepArray = Array("IS_CheckUpdates", "IS_InstallNET", "IS_InstallJRE", "IS_Addons", "IS_PostSSRS")
	Else
		LogEvent "No InstallType for " & strType
		ScriptQuit 1
	End If
	
ElseIf strType = "as_rms" _
Then 

	If strMode = "install" _ 
	Then
		strStepArray = Array("IS_CheckUpdates", "IS_InstallNET", "IS_InstallIIS", "IS_InstallJRE", "IS_CreateServiceAccount", "IS_InstallSQL", "IS_InstallSSMS", "IS_CreateSQLDB", "IS_CreateSQLUser", "IS_FillDatabase", "IS_InstallRMS", "IS_ReplaceIPRegistry", "IS_ReplaceIPHierarchy", "IS_PostIIS", "IS_PostIISAS", "IS_Addons", "IS_PostSSRS", "IS_InstallPortal", "IS_InstallDNA", "IS_InstallOWC", "IS_PostInstall")
	ElseIf strMode = "upgrade" _
	Then
		strStepArray = Array("IS_CheckUpdates", "IS_InstallNET", "IS_InstallIIS", "IS_InstallJRE", "IS_InstallSQL", "IS_InstallSSMS", "IS_DatabaseMigration", "IS_FillDatabase", "IS_InstallPrePatch", "IS_UpgradeRMS", "IS_ReplaceIPRegistry", "IS_ReplaceIPHierarchy", "IS_PostIIS", "IS_PostIISAS", "IS_Addons", "IS_PostSSRS", "IS_InstallPortal", "IS_InstallDNA", "IS_InstallOWC", "IS_PostInstall")
	ElseIf strMode = "refresh" _
	Then
		strStepArray = Array("IS_CheckUpdates", "IS_InstallNET", "IS_InstallJRE", "IS_Addons", "IS_PostSSRS")
	Else
		LogEvent "No InstallType for " & strType
		ScriptQuit 1
	End If
	
ElseIf strType = "ds" Then
	
	If strMode = "install" _ 
	Then
		strStepArray = Array("IS_CheckUpdates", "IS_InstallNET", "IS_InstallIIS", "IS_InstallJRE", "IS_InstallDS", "IS_ReplaceIPRegistry", "IS_PostIIS", "IS_Addons", "IS_InstallPortal", "IS_PostInstall")
	ElseIf strMode = "upgrade" _
	Then
		strStepArray = Array("IS_CheckUpdates", "IS_InstallNET", "IS_InstallIIS", "IS_InstallJRE", "IS_InstallDS", "IS_ReplaceIPRegistry", "IS_PostIIS", "IS_Addons", "IS_InstallPortal", "IS_PostInstall")
	ElseIf strMode = "refresh" _
	Then
		strStepArray = Array("IS_CheckUpdates", "IS_InstallNET", "IS_InstallJRE", "IS_Addons")
	Else
		LogEvent "No InstallType for " & strType
		ScriptQuit 1
	End If

ElseIf strType = "custom" Then
	
	strStepArray = Array("IS_CheckUpdates", "IS_InstallNET", "IS_InstallIIS", "IS_InstallJRE" )
	
Else
	' Minimal Prerequisite
	strStepArray = Array("IS_CheckUpdates", "IS_InstallNET", "IS_InstallIIS", "IS_InstallJRE" )
End If



' ---------------------------------------------------------------------------------------------------
' Parameter Summary
' ---------------------------------------------------------------------------------------------------

LogEvent "----------------------------------------------------------"
Logevent "System Parameter"
LogEvent "----------------------------------------------------------"
If strComputer <> "" Then LogEvent "Computer Name: " & strComputer End IF
If strOSArch <> "" Then LogEvent "OS Architecture: " & strOSArch End IF
If strOSVersion <> "" Then LogEvent "OS Version: " & strOSVersion End IF
If strOSCaption <> "" Then LogEvent "OS Caption: " & strOSCaption End IF
If strOSServicePack <> "" Then LogEvent "OS Service Pack: " & strOSServicePack End IF
If strOSPath <> "" Then LogEvent "OS Root: " & strOSPath End IF
If strIP <> "" Then LogEvent "IP Address: " & strIP End IF
If strAdministrators <> "" Then LogEvent "Local Administrators Group: " & strAdministrators End IF
If strSystemName <> "" Then LogEvent "Local SYSTEM Group: " & strSystemName End IF
LogEvent "Trusted Installer State: " & GetServiceState("TrustedInstaller")

LogEvent "----------------------------------------------------------"
Logevent "Setup Parameter"
LogEvent "----------------------------------------------------------"
If strInstallPath <> "" Then LogEvent "Install Path: " & strInstallPath End IF
If strMode <> "" Then LogEvent "Installation mode: " & strMode End IF
If strType <> "" Then LogEvent "Installation type: " & strType End IF
If strCustomMST <> "" Then LogEvent "Use Custom MST: " & strCustomMST End IF
If strDisplayMode <> "" Then LogEvent "Display mode: " & strDisplayMode End IF
If strPortalInstall <> "" Then LogEvent "Setup RayVentory Portal: " & strPortalInstall End IF
If strLicenseCounting <> "" Then LogEvent "Enable License Counting: " & strLicenseCounting End IF
If strActiveMQ <> "" Then LogEvent "Enable Messaging: " & strActiveMQ End IF
If strInstallMD <> "" Then LogEvent "Enable Managed Device: " & strInstallMD End IF
If strInstallDNA <> "" Then LogEvent "Setup DNA: " & strInstallDNA End IF
If strReplaceIP <> "" Then LogEvent "Replace Hostname : " & strReplaceIP End IF
If strWarehousePath <> "" Then LogEvent "Warehouse Folder: " & strWarehousePath End IF
If strIISProtocol <> "" Then LogEvent "IIS Protocol: " & strIISProtocol End IF
If strIISPort <> "" Then LogEvent "IIS Port Setting: " & strIISPort End IF
If strMGSDatabase <> "" Then LogEvent "Application Database: " & strMGSDatabase End IF
If strSVCAccountName <> "" Then LogEvent "Service Account Username: " & strSVCAccountName End IF
If strSVCAccountPwd <> "" Then LogEvent "Service Account Password: " & maskString(strSVCAccountPwd,1,1) End IF
If strSQLAdminGroup <> "" And (strMode = "install" Or strSQLInstallMode = "install") Then LogEvent "SQL Admin Group: " & strSQLAdminGroup End If
If strSQLInstallMode <> "" Then LogEvent "SQL Install Mode: " & strSQLInstallMode End IF
If strSQLInstanceName <> "" Then LogEvent "SQL Instance Name: " & strSQLInstanceName End IF
If strSQLCollation <> "" Then LogEvent "SQL Collation: " & strSQLCollation End IF
If strSSRSserverURL <> "" Then LogEvent "SSRS URL: " & strSSRSserverURL End IF

LogEvent "----------------------------------------------------------"
LogEvent "Script Parameter"
LogEvent "----------------------------------------------------------"
If strScriptVersion <> "" Then LogEvent "Script Version: " & strScriptVersion End IF
If isElevated <> "" Then LogEvent "Script is elevated: " & isElevated End IF
If strPath <> "" Then LogEvent "Script Path: " & strPath End IF
If strLogFolder <> "" Then LogEvent "Log Folder: " & strLogFolder End IF
If strIISVersionPath <> "" Then LogEventHide "Path for IIS config: " & strIISVersionPath, 1 End IF
If strOSSXSPath <> "" Then LogEventHide "Path for SXS source: " & strOSSXSPath, 1 End IF
If strSQLVersionPath <> "" Then LogEventHide "Path for SQL source: " & strSQLVersionPath, 1 End IF
If strSSMSVersionPath <> "" Then LogEventHide "Path for SSMS source: " & strSSMSVersionPath, 1 End IF
If LatestStep() <> "" Then LogEvent "Current step : " & LatestStep() End IF

LogEvent "----------------------------------------------------------"
'Wait 3 Seconds
'WScript.Sleep 3000

' ---------------------------------------------------------------------------------------------------
' Main Procedure
' ---------------------------------------------------------------------------------------------------
	
' Get Install Sequence
Dim i

' Always Check Prerequisites
IS_CheckPrereqs

' Check if Installation already ended

If LatestStep() = "End" _
Then
	LogEvent "----------------------------------------------------------"
	Logevent "Installation was already finished."
	Logevent "Last step """ & LatestStep() & """."
	LogEvent "----------------------------------------------------------"
	ScriptQuit 0
End If

' Call all other steps
For i = 0 To ubound(strStepArray)

	' Store Next Step
	If i < ubound(strStepArray) Then
		strNextStep = strStepArray(i+1)
	Else
		strNextStep = "End"
	End If
	
	LogEvent "----------------------------------------------------------"
	LogEvent ("Step : ") & TAB & strStepArray(i)
	LogEventHide ("Number : ") & TAB & i+1 & "/" & ubound(strStepArray)+1, 1
	LogEventHide ("Next : ") & TAB & strNextStep, 1
	LogEvent "----------------------------------------------------------"

	If ReadStep(strStepArray(i)) _
	Or ReadStep("") _
	Then
		Execute (strStepArray(i))
		If i = ubound(strStepArray) _
		Then
			NextStep("End")
		Else
			NextStep(strStepArray(i+1))
		End If
	Else
		LogEventHide "Skipping step", 1
	End If

Next

LogEvent "----------------------------------------------------------"
LogEvent "Installation completed successfully"
LogEvent "----------------------------------------------------------"

If requiredReboot() <> 0 Then initReboot "Reboot required! Restart now?", 0, ""  Else initReboot "Reboot recommended! Restart now?", 0, ""  End If
ScriptQuit 0

' ---------------------------------------------------------------------------------------------------
' Install Sequence -  Functions and Subs
' ---------------------------------------------------------------------------------------------------

Sub IS_CheckPrereqs

	FindSQLTools
	CheckPrereqs getOSVersion(strOSVersion) 

End Sub

Sub IS_CheckUpdates

	If CheckHotfixes(strHotFixesID) > 0 _
	Then				
		If requiredReboot() <> 0 _
		Then 
			initReboot "Hotfix requires reboot! Restart now?", 1, strNextStep
		End If
	End If

End Sub

Sub IS_InstallNET
	
	InstallNET getOSVersion(strOSVersion)
	If requiredReboot() <> 0 _
	Then 
		initReboot ".Net requires reboot! Restart now?", 1, strNextStep
	End If
End Sub

Sub IS_InstallIIS
	
	InstallIIS 	strIISVersionPath, strOSSXSPath
	If requiredReboot() <> 0 _
	Then 
		initReboot "IIS requires reboot! Restart now?", 1, strNextStep
	End If

End Sub

Sub IS_InstallJRE

	InstallJRE strPath

End Sub

Sub IS_CreateServiceAccount

	If strSVCLogonDomain = "local" _
	Then
		CreateServiceAccount strSVCAccountName, strSVCAccountPwd
	Else
		LogEventHide "Skipping step " & strStep, 1
	End If
		
End Sub

Sub IS_InstallSQL
	
	If strSQLInstallMode = "install" _
	Then
		'Install SQL Express
		InstallSQL strSQLAdminGroup, strSQLInstanceName, "SQL,RS,Tools,SNAC_SDK", strSQLVersionPath, strSQLCollation
	ElseIf strSQLInstallMode = "upgrade" _
	Then
		'Upgrade SQL Express
		UpgradeSQL strSQLInstanceName, strSQLVersionPath
		If requiredReboot() <> 0 _
		Then 
			initReboot "SQL requires reboot! Restart now?", 1, strNextStep
		End If
	Else
		LogEventHide "Skipping step " & strStep, 1
	End If

End Sub

Sub IS_InstallSSMS

	If ((strSQLInstallMode = "install" _
	And strSSMSVersionPath <> "") _
	Or strSQLInstallMode = "ssms") _
	Then
		InstallSSMS strSSMSVersionPath, strSQLVersionPath
	ElseIf (strSQLInstallMode = "upgrade" And strSSMSVersionPath <> "") _
	Then
		UpgradeSSMS strSSMSVersionPath, strSQLVersionPath
		If requiredReboot() <> 0 _
		Then 
			initReboot "SSMS requires reboot! Restart now?", 1, strNextStep
		End If
	Else
		LogEventHide "Skipping step " & strStep, 1
	End If
 
End Sub

Sub IS_CreateSQLDB

	If strSQLInstallMode = "none" _
	Or strSQLInstallMode = "ssms" _
	Then
		CreateSQLDB  strSQLFullInstanceName, strMGSDatabase, strSQLServerUser, strSQLServerPass
	Else
		LogEventHide "Skipping step " & strStep, 1
	End If
	
End Sub 

Sub IS_CreateSQLUser
	
	If strSQLInstallMode = "none" _
	Or strSQLInstallMode = "ssms" _
	Then
		CreateSQLUser strSQLFullInstanceName, strMGSDatabase, strSQLServerUser, strSQLServerPass, strSVCAccountName, strSVCAccountPwd 
	Else
		LogEventHide "Skipping step " & strStep, 1
	End If
	
End Sub 

Sub IS_FillDatabase

	If strSQLInstallMode = "none" _ 
	Or strSQLInstallMode = "ssms" _
	Then
		'CreateSQLTables strSQLFullInstanceName, strMGSDatabase, strSQLServerUser, strSQLServerPass, strSVCAccountName
		'CreateSQLTables strSQLFullInstanceName, strMGSDatabase, strSQLServerUser, strSQLServerPass
		FillDatabase strSQLFullInstanceName, strMGSDatabase, strSQLServerUser, strSQLServerPass, strSVCAccountName 
	Else
		LogEventHide "Skipping step " & strStep, 1
	End If
	
End Sub

Sub IS_DatabaseMigration
	
	If isBlank(strSQLServerUser) _
	And isBlank(strSQLServerUser) _
	Then
		DatabaseMigration strSQLFullInstanceName, strMGSDatabase, "", ""
	ElseIf Not isBlank(strSQLServerUser) And Not isBlank(strSQLServerUser)_
	Then
		DatabaseMigration strSQLFullInstanceName, strMGSDatabase, strSQLServerUser, strSQLServerPass
	Else
		LogEventHide "Skipping step " & strStep, 1
	End If
	
End Sub

Sub IS_InstallPrePatch
	
	If getEtapInstallVersion() = "10.40.1646" _
	Then
		InstallPrePatch strInstallPath, strSVCAccountName, strSVCAccountPwd, strMGSDatabase, strComputer, strSQLFullInstanceName, "", ""
	Else
		LogEventHide "Skipping step " & strStep, 1
	End If
	
End Sub

Sub IS_InstallRV
	
	If not isBlank(getEtapInstallDir()) _
	Then
		LogEvent "Install path found!"
		LogEvent "Change installation mode to upgrade or refresh."
		LogEvent "Exiting..."
		ScriptQuit 1
	ElseIf not isBlank(getWarehouse())  _
	Then
		LogEvent "Warehousepath found!"
		LogEvent "Change installation mode to upgrade or refresh."
		LogEvent "Exiting..."
		ScriptQuit 1
	ElseIf strSQLInstallMode = "none" Or strSQLInstallMode = "ssms" _
	Then	
		InstallRV strInstallPath, strSVCAccountName, strSVCAccountPwd, strMGSDatabase, strComputer, strSQLFullInstanceName, strSVCAccountName, strSVCAccountPwd, strCustomMST
	Else
		InstallRV strInstallPath, strSVCAccountName, strSVCAccountPwd, strMGSDatabase, strComputer, strSQLFullInstanceName, "", "", strCustomMST
	End If
	
End Sub

Sub IS_UpgradeRV

	If strSQLInstallMode = "none" Or strSQLInstallMode = "ssms" _
	Then
		InstallRV strInstallPath, strSVCAccountName, strSVCAccountPwd, strMGSDatabase, strComputer, strSQLFullInstanceName, strSVCAccountName, strSVCAccountPwd, strCustomMST
	Else
		InstallRV strInstallPath, strSVCAccountName, strSVCAccountPwd, strMGSDatabase, strComputer, strSQLFullInstanceName, "", "", strCustomMST
	End If
	
End Sub

Sub IS_InstallRMS
	strStep = "IS_InstallRMS"

' Nothing to do right now
	
End Sub

Sub IS_UpgradeRMS
	strStep = "IS_InstallRMS"

' Nothing to do right now
	
End Sub

Sub IS_InstallDS

	InstallDS strInstallPath, strWarehousePath, strComputer, strJobParent, strJobProtocol, strImportParent, strImportParentSQL, strImportUser , strImportPass, strImportTypes, strCustomMST
	
End Sub

Sub IS_ReplaceIPHierarchy
' Replace Computername by IP in Hierarchy/Reporting
	
	If strReplaceIP <> "false" _
	Then
		ReplaceIPHierarchy strComputer, strIP
		AddIPSSRSURL strIP
	Else
		LogEventHide "Skipping step " & strStep, 1
	End If

End Sub

Sub IS_ReplaceIPRegistry
' Replace Computername by IP in Registry
	
	If strReplaceIP <> "false" _
	Then
	ReplaceIPRegistry strOSArch, strIP
	Else
		LogEventHide "Skipping step " & strStep, 1
	End If

End Sub

Sub IS_PostIIS
' General postconfigurution for IIS
	
	Unlock "basicAuthentication"
	Unlock "windowsAuthentication"
	Unlock "anonymousAuthentication"
	
End Sub

Sub IS_PostIISAS
' Postconfigure IIS for Administration Server
	
	AuthManageSoftRP "basicAuthentication", false
	AuthManageSoftRP "windowsAuthentication", true
		
End Sub

Sub IS_InstallOWC
' Install Office Web Components

	InstallOWC strPath

End Sub

Sub IS_PostInstall
' Post Installations
	
	'Check if NetGroup Packet Filter (WinPCAP) ist running
	If GetServiceState("npf") = "Running" _
	Then
		'Start local port scan
		MgsIPScan "localhost"
		MgsIPScan strComputer
		MgsIPScan strIP
	End If
	
End Sub

Sub IS_Addons
' Post Installations

	'Stop all Services before doing anything
	SetAllRVServicesState "Stopped"
	If strType = "as_rv" _
	Or strType = "as_rms" _
	Or strType = "custom" _
	Then
		
		DecompressAddon strPath & "Utils\Addon\AS_AgentsFix.7z", strWarehousePath
		DecompressAddon strPath & "Utils\Addon\AS_ProgramFilesFix.7z", strInstallPath
		DecompressAddon strPath & "Utils\Addon\AS_WarehouseFix.7z", strWarehousePath
		AddonsAS strSQLFullInstanceName, strMGSDatabase, strSQLServerUser, strSQLServerPass
		If strLicenseCounting = "true" _
		Then
			LicenseCounting strSQLFullInstanceName, strMGSDatabase, strSQLServerUser, strSQLServerPass, "enable"
		ElseIf strLicenseCounting = "false" _
		Then
			LicenseCounting strSQLFullInstanceName, strMGSDatabase, strSQLServerUser, strSQLServerPass, "disable"
		End If
	ElseIf strType = "ds" _
	Then
		DecompressAddon strPath & "Utils\Addon\DS_ProgramFilesFix.7z", strInstallPath
	End If
	Addons()
	'Start all Services to continue
	SetAllRVServicesState "Started"

End Sub

Sub IS_PostSSRS
' Postconfigure SSRS / Deploy Reports 

			LogEvent "Setup Reporting"
			
	If strSQLInstallMode = "sql" _
	Or strSQLInstallMode = "sqlssms" _
	Then
		SetRMSSSRSLocation strSSRSserverURL, strSSRSServerUser, strSSRSServerPass
	End If
	
	LogEvent "Reports for Asset and Reporting"
	DeployReports strInstallPath & "\Reporter\Examples\PrintableReports", strInstallPath, strSQLFullInstanceName, strMGSDatabase, strSQLServerUser, strSQLServerPass, strSSRSserverURL, strSSRSServerUser, strSSRSServerPass
	
	LogEvent "Reports for SSRS Reporting"
	DeployReports strInstallPath & "\Reporter\Examples\RMSReporting", strInstallPath, strSQLFullInstanceName, strMGSDatabase, strSQLServerUser, strSQLServerPass, strSSRSserverURL, strSSRSServerUser, strSSRSServerPass
	
	LogEvent "Reports from Addon Folder"
	DeployReports strPath & "Utils\Addon\Reports", strInstallPath, strSQLFullInstanceName, strMGSDatabase, strSQLServerUser, strSQLServerPass, strSSRSserverURL, strSSRSServerUser, strSSRSServerPass

End Sub

Sub IS_InstallPortal

	If strPortalInstall = "true" _
	Then
		InstallPortal
	Else
		LogEventHide "Skipping step " & strStep, 1
	End If

End Sub

Sub IS_InstallDNA

	If strInstallDNA = "true" _
	Then
		InstallDNA
	Else
		LogEventHide "Skipping step " & strStep, 1
	End If

End Sub


' ---------------------------------------------------------------------------------------------------
' General Functions and Subs
' ---------------------------------------------------------------------------------------------------

Sub LogEvent (strMessage)
	LogEventHide strMessage, 0
End Sub 

Sub LogEventHide (strMessage, strhidden)
' This sub displays log messages and writes log file

	Dim objLogFSO 
	Dim objLogFile

	Set objLogFSO = CreateObject("Scripting.FileSystemObject")
	
	If Not (objLogFSO.FolderExists(strLogFolder)) Then objLogFSO.CreateFolder(strLogFolder)
	
	If objLogFSO.FileExists(strLogFile) Then
	  Dim objFile
	  Set objFile = objLogFSO.GetFile(strLogFile)
	  If objFile.Size > 10000000 Then    
		objLogFSO.DeleteFile strLogFile
	  End If
	  Set objFile = Nothing
	End If 

	Set objLogFile = objLogFSO.OpenTextFile(strLogFile, 8, True)

	If (strDisplayMode <> "quiet" And strDisplayMode = "standard" And strhidden = 0) Or strDisplayMode = "verbose" Then WScript.Echo Date() & " " & Time() & " " & strMessage End If
	objLogFile.WriteLine(Date() & " " & Time() & " " & strMessage)

	objLogFile.Close

	Set objLogFile = Nothing
	Set objLogFSO = Nothing

End Sub

Function ReadStep(p_step)

	ReadStep = False
	
	' Check if Step is Array or Blank (first step)
	If ((FindTextAfterStringInFile (strIniFile, "InstallStep=") = p_step) AND (inArray(p_step, strStepArray) = True)) _
	Or (isBlank(p_step) AND isBlank(FindTextAfterStringInFile (strIniFile, "InstallStep="))) _
	Then 
		ReadStep = True
	End If
		
End Function

Function LatestStep()

	LatestStep = FindTextAfterStringInFile (strIniFile, "InstallStep=")
		
End Function

Sub NextStep (p_NextStep)
	
	LogEventHide "----------------------------------------", 1
	LogEventHide "Next Step " & p_NextStep, 1
	ReplaceTextInFileRegExp strIniFile, "InstallStep=", "InstallStep=" & p_NextStep
	LogEventHide "----------------------------------------", 1
End Sub

Sub MgsIPScan(p_target)
	
	LogEvent "Starting MgsIPScan on " & p_target
	
	strProcess = "MgsIPScan.exe"
	strParam = "-T4 -v --version-all --privileged -sT -oN=" & strLogFolder & "\MgsIPScan_" & p_target & ".log " & p_target
	strFolder = strInstallPath & "\RemoteExecution\MgsIPScan"
		
	ExecuteProcessPath strProcess, strParam, strFolder, 1, 0

End Sub

Function FindTextAfterStringInFile (p_FilePath, p_Text)
' Find Text in File and return value after

	Dim objFSO
	Dim objFile
	Dim textFile
	Dim objMatch
	Dim objRE : Set objRE = New RegExp 

	Set objFSO = CreateObject("Scripting.FileSystemObject")
	
	'LogEventHide "Read File: " & p_FilePath, 1 

	Set objFile = objFSO.OpenTextFile(p_FilePath, 1)
	textFile = objFile.ReadAll
	objFile.Close

	objRE.Pattern = p_Text & "\S*" 
	objRE.IgnoreCase = True 

	Set objMatch = objRE.Execute(textFile)
	If objMatch.Count = 1 Then
		FindTextAfterStringInFile = replace(objMatch.Item(0).Value, p_Text, "")
	Else
		LogEventHide "Searchstring was not found """ & p_Text & """.", 1
		Set objRE = Nothing
		ScriptQuit 1
	End If

	Set objMatch = Nothing
	Set objRE = Nothing

End Function

Sub ReplaceTextInFile (p_FilePath, p_OrgText, p_NewText)
' Replace p_OrgText in p_FilePath with p_NewText

	Dim objFSO
	Dim objFile
	Dim OrgFile
	Dim NewFile

	Set objFSO = CreateObject("Scripting.FileSystemObject")
	
	'LogEventHide "Read File: " & p_FilePath, 1 

	Set objFile = objFSO.OpenTextFile(p_FilePath, 1)
	OrgFile = objFile.ReadAll
	objFile.Close

	'LogEventHide "Replace " & p_OrgText & " with " & p_NewText, 1 

	NewFile = Replace(OrgFile, p_OrgText, p_NewText)

	'LogEventHide "Write File: " & p_FilePath, 1 
	
	Set objFile = objFSO.OpenTextFile(p_FilePath, 2)
	objFile.WriteLine NewFile
	objFile.Close

End Sub

Sub ReplaceTextInFileRegExp (p_FilePath, p_OrgText, p_NewText)
' Replace starting p_OrgText in p_FilePath with p_NewText

	Dim objFSO
	Dim objFile
	Dim OrgFile
	Dim NewFile
	Dim objRE : Set objRE = New RegExp 

	Set objFSO = CreateObject("Scripting.FileSystemObject")
	
	'LogEventHide "Read File: " & p_FilePath, 1 

	Set objFile = objFSO.OpenTextFile(p_FilePath, 1)
	OrgFile = objFile.ReadAll
	objFile.Close

	'LogEventHide "Replace " & p_OrgText & " with " & p_NewText, 1 


	objRE.Pattern = p_OrgText & "\S*" 
	objRE.IgnoreCase = True
	objRE.Global = False
	NewFile = objRE.Replace(OrgFile, p_NewText) 

	'LogEventHide "Write File: " & p_FilePath, 1 
	
	Set objFile = objFSO.OpenTextFile(p_FilePath, 2)
	objFile.WriteLine NewFile
	objFile.Close

End Sub


Function ReadIni( myFilePath, mySection, myKey, bNull )
    ' This function returns a value read from an INI file
    '
    ' Arguments:
    ' myFilePath  [string]  the (path and) file name of the INI file
    ' mySection   [string]  the section in the INI file to be searched
    ' myKey       [string]  the key whose value is to be returned
	' bNull       [bool]    if true, value can be null
    '
    ' Returns:
    ' the [string] value for the specified key in the specified section
    '

    Const ForReading   = 1
    Const ForWriting   = 2
    Const ForAppending = 8

    Dim intEqualPos
    Dim objIniFSO, objIniFile
    Dim strFilePath, strKey, strLeftString, strLine, strSection

    Set objIniFSO = CreateObject( "Scripting.FileSystemObject" )

    ReadIni     = ""
    strFilePath = Trim( myFilePath )
    strSection  = Trim( mySection )
    strKey      = Trim( myKey )

    If objIniFSO.FileExists( strFilePath ) Then
        Set objIniFile = objIniFSO.OpenTextFile( strFilePath, ForReading, False )
        Do While objIniFile.AtEndOfStream = False
            strLine = Trim( objIniFile.ReadLine )

            ' Check if section is found in the current line
            If LCase( strLine ) = "[" & LCase( strSection ) & "]" Then
                strLine = Trim( objIniFile.ReadLine )

                ' Parse lines until the next section is reached
                Do While Left( strLine, 1 ) <> "["
                    ' Find position of equal sign in the line
                    intEqualPos = InStr( 1, strLine, "=", 1 )
                    If intEqualPos > 0 Then
                        strLeftString = Trim( Left( strLine, intEqualPos - 1 ) )
                        ' Check if item is found in the current line
                        If LCase( strLeftString ) = LCase( strKey ) Then
                            ReadIni = Trim( Mid( strLine, intEqualPos + 1 ) )
                            ' In case the item exists but value is blank
                            ' Abort loop when item is found
                            Exit Do
                        End If
                    End If

                    ' Abort if the end of the INI file is reached
                    If objIniFile.AtEndOfStream Then Exit Do

                    ' Continue with next line
                    strLine = Trim( objIniFile.ReadLine )
                Loop
            Exit Do
            End If
        Loop
        objIniFile.Close

		If ReadIni = "" AND NOT bNull Then
			LogEvent "Reading " & myKey & " parameter failed."
			LogEvent "Exiting..."
			ScriptQuit 1
		End If	
		
    Else
        LogEvent strFilePath & " doesn't exists. Exiting..."
        ScriptQuit 1
    End If
	
	Set objIniFSO = Nothing
	Set objIniFile = Nothing
	
End Function

REM Call GetWMIRSOBject( ".", "Root\Microsoft\SqlServer\ReportServer")
REM Sub GetWMIRSOBject ( strComputer, WMINameSpace)
	REM Dim objWMIService
	REM Dim objOutParams
	REM Dim rsInstance
	REM Dim rsVersion
	
	REM rsInstance = GetWMINameSpaceSubObjectName ( strComputer, WMINameSpace)
	REM rsVersion = GetWMINameSpaceSubObjectName ( strComputer, WMINameSpace & "\" & rsInstance)

	REM Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\" & WMINameSpace & "\" & rsInstance & "\" & rsVersion & "\Admin")
	REM Set objOutParams = objWMIService.ReserveURL("ReportServerWebService","http://192.168.42.21:80",1033)
	
	
REM End Sub

REM Function GetWMINameSpaceSubObjectName ( strComputer, WMINameSpace)
	REM Dim objWMIService
	REM Dim colNameSpaces
	REM Dim colNameSpacesCount
		
	REM Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\" & WMINameSpace)
	REM Set colNameSpaces = objWMIService.InstancesOf("__NAMESPACE")
	REM colNameSpacesCount = colNameSpaces.Count 
	
	REM For Each objNameSpace In colNameSpaces
		REM colNameSpacesCount = colNameSpacesCount - 1

		REM If colNameSpacesCount = 0 Then 
			REM GetWMINameSpaceSubObjectName = objNameSpace.Name
		REM End If
    REM Next
	
REM End Function

Function GetWMIProperty( strComputer, WMIClass, WMIProperty )
    ' This function returns a value read from a WMI property
    '
    ' Arguments:
    ' WMIClass      [string]  name of the WMI class, i.e. Win32_OperatingSystem
    ' WMIProperty   [string]  name of the WMI property, i.e. OSArchitecture
    '

	Dim objWMIService
	Dim objWMIItems
	Dim objWMIItem
		
	Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
	Set objWMIItems = objWMIService.ExecQuery ("SELECT " & WMIProperty & " from " & WMIClass)

	For Each objWMIItem In objWMIItems

		GetWMIProperty = objWMIItem.Properties_.Item(WMIProperty)

	Next

	Set objWMIService = Nothing
	Set objWMIItems = Nothing
	Set objWMIItem = Nothing

	If GetWMIProperty = "" Then
		LogEvent "Reading " & WMIClass & "\" & WMIProperty & " failed."
		LogEvent "Exiting..."
		ScriptQuit 1
	End If
	
End Function

Function GetIPAddress ( strComputer )
    ' This function returns an IP address of the local computer from an interface with a default gateway set
    '
	' Arguments:
	' strComputer   [string]  computer name

	Dim ObjWMIService
	Dim ObjWMIItems
	Dim ObjWMIItem
	Dim strGW

	Set objWMIService = GetObject("winmgmts:" _
	 & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
	Set objWMIItems = objWMIService.ExecQuery ("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")

	For Each objWMIItem In objWMIItems

		strIP = objWMIItem.IPAddress(0)
		'strGW = objWMIItem.DefaultIPGateway(0)

	If TypeName(strGW) <> "Error" Then
	
		GetIPAddress = strIP

	End If

	Next
	
	Set objWMIService = Nothing
	Set objWMIItems = Nothing
	Set objWMIItem = Nothing

	If strIP = "" Then
		LogEvent "Cannot determine an IP address"
		LogEvent "Exiting..."
		ScriptQuit 1
	End If
	
End Function

Function GetEnvVariable (strVarName)
    ' This function returns a value read from an OS variable
    '
    ' Arguments:
    ' strVarName      [string]  name of the variable, i.e. PATH, PROGRAMFILES, etc

	Dim objShell
	Dim objEnv

	Set objShell = CreateObject("WScript.Shell")
	Set objEnv = objShell.Environment("PROCESS")

	GetEnvVariable = objEnv(strVarName)

	If GetEnvVariable = "" Then
		LogEvent "Failed to get system environment variable " & strVarName
		ScriptQuit 1
	End If

	Set objShell = Nothing

End Function

Sub ExecutePSS (p_scriptname, p_scriptparameter)
	'This sub executes Powershell scripts
	
	strProcess = strOSPath & "\System32\WindowsPowershell\v1.0\powershell.exe"
	strParam = "-ExecutionPolicy Bypass -NoLogo -NoProfile -NonInteractive -File " & p_scriptname & " " & p_scriptparameter
	
	ExecuteProcess strProcess, strParam

End Sub

Sub ExecuteProcessPath (p_Process, p_Param, p_Folder, p_NoWait, p_NoError)
   ' This sub executes a process and checks an exit code
    ' If exit code is other than zero, the executions fails
    '
    ' strVarName      [string]  name of the variable, i.e. PATH, PROGRAMFILES, etc

	Dim rc
	Dim strCommand
	Dim objShell
	Dim objEnv
	Dim errorCodes 
	
	' Executing
	Set objShell = CreateObject("WScript.Shell")
	Set objEnv = objShell.Environment("PROCESS")
	If isBlank(p_Folder) Then p_Folder = strDefaultPath

	If isBlank(p_Process) Then
		strCommand = p_Param 
	Else
		strCommand = """" & p_Process & """" & " " & p_Param 
	End If
	
	If p_NoWait = 1 Then strCommand = "cmd /C start """" " & strCommand
	
	LogEventHide "Executing: " & strCommand & " in " & p_Folder, 1

	objShell.CurrentDirectory = p_Folder
	objEnv("SEE_MASK_NOZONECHECKS") = 1

	If strDisplayMode = "verbose" Then
		rc = objShell.Run(strCommand, 1, True)
	Else
		rc = objShell.Run(strCommand, 0, True)
	End If
	
	If rc = 1626 Then
		LogEvent "! Process exiting with status " & rc
		initReboot "Reboot pending. Restart now?", 1, ""
		ScriptQuit rc
	ElseIf (rc <> 0 And rc <> 128 And rc <> 3010) And p_NoError <> 1 Then
		LogEvent "! Process exiting with status " & rc
		LogEvent "! Aborting..."
		ScriptQuit rc
	ElseIf (rc = 3010) Then
		strRebootRequired = strRebootRequired + 1
		LogEventHide "Execution successful reboot required. Returncode: " & rc, 1
	Else
		LogEventHide "Execution successful. Returncode: " & rc, 1
	End If

	objEnv.Remove("SEE_MASK_NOZONECHECKS")
	Set rc = Nothing
	Set objShell = Nothing
	Set objEnv = Nothing

End Sub

Function ExecStdOut(strProcess, strParam, strFolder)

	Dim rc
	Dim strCommand
	Dim objShell
	Dim objEnv

	Set objShell = CreateObject("WScript.Shell")
	Set objEnv = objShell.Environment("PROCESS")
	strCommand = """" & strProcess & """" & " " & strParam 
	LogEventHide "Executing: " & strCommand & " in " & strFolder, 1

	objShell.CurrentDirectory = strFolder
	objEnv("SEE_MASK_NOZONECHECKS") = 1
	Set rc = objShell.Exec(strCommand)

	Do While rc.Status = 0 
    		WScript.Sleep 100 
	Loop 

	If rc.ExitCode <> 0 Then
		LogEvent "! Process exiting with status " & rc
		LogEvent "! Aborting..."
		ScriptQuit rc.ExitCode
	Else
		LogEventHide "Execution successful", 1
		ExecStdOut = rc.StdOut.ReadAll
	End If

	objEnv.Remove("SEE_MASK_NOZONECHECKS")
	Set rc = Nothing
	Set objShell = Nothing
	Set objEnv = Nothing
   
End Function 

Sub ExecuteProcess (p_Process, p_Param)
    ' This sub executes a process and checks an exit code
    ' If exit code is other than zero, the executions fails
    '
    ' strVarName      [string]  name of the variable, i.e. PATH, PROGRAMFILES, etc

	ExecuteProcessPath p_Process, p_Param, strDefaultPath, 0, 0
  
End Sub

Sub InstallIIS (p_IISVersionPath, p_OSSXSPath)
	' This sub triggers the installation of IIS depending on which OS is the script being run on
	'
	' Arguments:
	' p_IISVersionPath	[sting] e.g. strPath & "Utils\config2012.xml"
	' p_OSSXSPath [sting] e.g. strPath & "Utils\Sources\sxs\2012.7z"

	If p_OSSXSPath <> "" Then
		LogEvent "Decompressing SXS"
	
		strProcess = strPath & "Utils\Tools\7za.exe"
		strParam = "x """ & p_OSSXSPath & """" &_
			" -o""" & strPath & "Utils\Sources\sxs""" &_
			" -y"
		ExecuteProcess strProcess, strParam
	End If
	
	LogEvent "IIS Installation"
	LogEvent "This may take more than 15 Minutes..."
	
	If p_IISVersionPath = "LegacyIIS7" Then
		If requiredReboot() <> 0 Then 
			initReboot "Reboot required! Restart now?", 1, ""
		End If
		
		strProcess = "%windir%\system32\pkgmgr.exe"
		strParam = "/iu:" & _
		"IIS-WebServerRole;" & _
		"IIS-WebServer;" & _
		"IIS-CommonHttpFeatures;" & _
		"IIS-StaticContent;" & _
		"IIS-DefaultDocument;" & _
		"IIS-DirectoryBrowsing;" & _
		"IIS-HttpErrors;" & _
		"IIS-ApplicationDevelopment;" & _
		"IIS-ASPNET;" & _
		"IIS-NetFxExtensibility;" & _
		"IIS-ISAPIExtensions;" & _
		"IIS-ISAPIFilter;" & _
		"IIS-HealthAndDiagnostics;" & _
		"IIS-HttpLogging;" & _
		"IIS-RequestMonitor;" & _
		"IIS-Security;" & _
		"IIS-BasicAuthentication;" & _
		"IIS-WindowsAuthentication;" & _
		"IIS-RequestFiltering;" & _
		"IIS-Performance;" & _
		"IIS-HttpCompressionStatic;" & _
		"IIS-HttpCompressionDynamic;" & _
		"IIS-WebServerManagementTools;" & _
		"IIS-ManagementConsole;" & _
		"IIS-ManagementScriptingTools;" & _
		"IIS-ManagementService;" & _
		"IIS-IIS6ManagementCompatibility;" & _
		"IIS-Metabase;" & _
		"IIS-WMICompatibility;" & _
		"IIS-LegacyScripts;" & _
		"IIS-LegacySnapIn;" & _
		"WAS-WindowsActivationService;" & _
		"WAS-ProcessModel;" & _
		"WAS-NetFxEnvironment;" & _
		"WAS-ConfigurationAPI"
	
		ExecuteProcess strProcess, strParam
	
		LogEvent "Installing WebDAV for IIS 7.0"
	
		strProcess = "%windir%\system32\msiexec.exe"
		
			If LCase(strOSArch) = "32-bit" Then
				strParam = "/i """ & strPath & "Utils\Sources\installer\webdav_x86_75.msi"" " & strUILevelMSI
			Else
				strParam = "/i """ & strPath & "Utils\Sources\installer\webdav_x64_75.msi"" " & strUILevelMSI
			End If
			
		ExecuteProcess strProcess, strParam
		
		LogEvent "Enabling WebDAV"
		
		strProcess = "%windir%\system32\inetsrv\appcmd.exe"
		strParam = "set config ""Default Web Site/"" /section:system.webServer/webdav/authoring /enabled:true /commit:apphost"
	
		ExecuteProcess strProcess, strParam	
		
	ElseIf p_IISVersionPath <> "" Then
		strSubLogFile = strLogFolder & "\ServerConfigRT_" & strOS & ".log"
		strProcess = strPath & "Utils\Tools\ServerConfigRT.exe"
		strParam = "-configurationfile """ & p_IISVersionPath & ""
		If strDisplayMode <> "verbose" Then
			strParam = strParam & """ -usefilelogger """ & strSubLogFile & """"
		End If
		
		ExecuteProcess strProcess, strParam
		ConfigureIIS
		
	Else
		LogEvent "Parameter p_IISVersionPath missing. Exiting..."
		ScriptQuit 1
		
	End If

End Sub

Sub ConfigureIIS

	Dim i, path, found, addElement
	Dim adminManager
	Dim windowsAuthenticationSection, requestFilteringSection
	Dim authoringSection, authoringRulesSection, authoringRulesCollection
	Dim isapiCgiRestrictionSection, isapiCgiRestrictionCollection
	Dim applicationPoolsSection, applicationPoolDefaultsElement
	
	LogEvent "IIS Configuration"

	LogEvent "Enable Windows Authentication"
	IISconfigureSection "system.webServer/security/authentication/windowsAuthentication", "", "MACHINE/WEBROOT/APPHOST/", "enabled", true
		
	LogEvent "Enable WebDAV Authoring / disable SSL requirement"
	IISconfigureSection "system.webServer/webdav/authoring", "MACHINE/WEBROOT/APPHOST/", "MACHINE/WEBROOT/APPHOST/Default Web Site", "enabled", true
	IISconfigureSection "system.webServer/webdav/authoring", "MACHINE/WEBROOT/APPHOST/", "MACHINE/WEBROOT/APPHOST/Default Web Site", "requireSsl", false
	
	LogEvent "Allow Unkown MIME Types for WebDAV"
	IISconfigureSection "system.webServer/webdav/authoringRules", "MACHINE/WEBROOT/APPHOST/", "MACHINE/WEBROOT/APPHOST/Default Web Site", "allowNonMimeMapFiles", true

	LogEvent "Allow double escaping"
	IISconfigureSection "system.webServer/security/requestFiltering", "", "MACHINE/WEBROOT/APPHOST/Default Web Site", "allowDoubleEscaping", true
	
	Set adminManager = CreateObject("Microsoft.ApplicationHost.WritableAdminManager")
	adminManager.CommitPath = "MACHINE/WEBROOT/APPHOST"

	' WebDAV create authoring rule
	Set authoringRulesSection = adminManager.GetAdminSection("system.webServer/webdav/authoringRules", "MACHINE/WEBROOT/APPHOST/Default Web Site")
	Set authoringRulesCollection = authoringRulesSection.Collection
	
	If Not authoringRulesCollection Is Nothing Then
	
		path = "*"
		For i=0 to CInt(authoringRulesCollection.count) -1
			If authoringRulesCollection.Item(i).Properties.Item("path").Value = path Then found = 1
		Next
		If Not found = 1 Then
			Set addElement = authoringRulesCollection.CreateNewElement("add")
			addElement.Properties.Item("roles").Value = "*"
			addElement.Properties.Item("path").Value = "*"
			addElement.Properties.Item("access").Value = "Read, Write, Source"
			authoringRulesCollection.AddElement(addElement)
		End If
		found = 0
		
	End If

	
	' Allow WebDAV / ASP.NET / Not listed CGI and ISAPI
	Set isapiCgiRestrictionSection = adminManager.GetAdminSection("system.webServer/security/isapiCgiRestriction", "MACHINE/WEBROOT/APPHOST/")
	isapiCgiRestrictionSection.Properties.Item("notListedCGIsAllowed").Value = True
	isapiCgiRestrictionSection.Properties.Item("notListedIsapisAllowed").Value = True

	Set isapiCgiRestrictionCollection = isapiCgiRestrictionSection.Collection
	If Not isapiCgiRestrictionCollection Is Nothing Then
		
		path = "\system32\inetsrv\webdav.dll"
		For i=0 to CInt(isapiCgiRestrictionCollection.count) -1
			If 	isapiCgiRestrictionCollection.Item(i).Properties.Item("path").Value = strOSPath & path Or _
				isapiCgiRestrictionCollection.Item(i).Properties.Item("path").Value = "%windir%" & path Then found = 1
		Next
		If Not found = 1 Then
			Set addElement = isapiCgiRestrictionCollection.CreateNewElement("add")
			addElement.Properties.Item("path").Value = strOSPath & path
			addElement.Properties.Item("allowed").Value = True
			addElement.Properties.Item("description").Value = "WEBDAV"
			addElement.Properties.Item("groupId").Value = "WEBDAV"
			isapiCgiRestrictionCollection.AddElement(addElement)
			Set addElement = isapiCgiRestrictionCollection.CreateNewElement("add")
		End If
		found = 0
		
		path = "\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll"
		For i=0 to CInt(isapiCgiRestrictionCollection.count) -1
			If 	isapiCgiRestrictionCollection.Item(i).Properties.Item("path").Value = strOSPath & path Or _
				isapiCgiRestrictionCollection.Item(i).Properties.Item("path").Value = "%windir%" & path Then found = 1
		Next
		If Not found = 1 Then
			Set addElement = isapiCgiRestrictionCollection.CreateNewElement("add")
			addElement.Properties.Item("path").Value = strOSPath & path
			addElement.Properties.Item("allowed").Value = True
			addElement.Properties.Item("description").Value = "ASP.NET v2.0.50727"
			addElement.Properties.Item("groupId").Value = "ASP.NET v2.0.50727"
			isapiCgiRestrictionCollection.AddElement(addElement)
			Set addElement = isapiCgiRestrictionCollection.CreateNewElement("add")
		End If
		found = 0
		
		path = "\Microsoft.NET\Framework64\v2.0.50727\aspnet_isapi.dll"
		For i=0 to CInt(isapiCgiRestrictionCollection.count) -1
			If 	isapiCgiRestrictionCollection.Item(i).Properties.Item("path").Value = strOSPath & path Or _
				isapiCgiRestrictionCollection.Item(i).Properties.Item("path").Value = "%windir%" & path Then found = 1
		Next
		If Not found = 1 Then
			Set addElement = isapiCgiRestrictionCollection.CreateNewElement("add")
			addElement.Properties.Item("path").Value = strOSPath & path
			addElement.Properties.Item("allowed").Value = True
			addElement.Properties.Item("description").Value = "ASP.NET v2.0.50727"
			addElement.Properties.Item("groupId").Value = "ASP.NET v2.0.50727"
			isapiCgiRestrictionCollection.AddElement(addElement)
			Set addElement = isapiCgiRestrictionCollection.CreateNewElement("add")
		End If
		found = 0
		
		path = "\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll"
		For i=0 to CInt(isapiCgiRestrictionCollection.count) -1
			If 	isapiCgiRestrictionCollection.Item(i).Properties.Item("path").Value = strOSPath & path Or _
				isapiCgiRestrictionCollection.Item(i).Properties.Item("path").Value = "%windir%" & path Then found = 1
		Next
		If Not found = 1 Then
			Set addElement = isapiCgiRestrictionCollection.CreateNewElement("add")
			addElement.Properties.Item("path").Value = strOSPath & path
			addElement.Properties.Item("allowed").Value = True
			addElement.Properties.Item("description").Value = "ASP.NET v4.0.30319"
			addElement.Properties.Item("groupId").Value = "ASP.NET v4.0.30319"
			isapiCgiRestrictionCollection.AddElement(addElement)
			Set addElement = isapiCgiRestrictionCollection.CreateNewElement("add")
		End If
		found = 0
		
		path = "\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll"
		For i=0 to CInt(isapiCgiRestrictionCollection.count) -1
			If 	isapiCgiRestrictionCollection.Item(i).Properties.Item("path").Value = strOSPath & path Or _
				isapiCgiRestrictionCollection.Item(i).Properties.Item("path").Value = "%windir%" & path Then found = 1
		Next
		If Not found = 1 Then
			Set addElement = isapiCgiRestrictionCollection.CreateNewElement("add")
			addElement.Properties.Item("path").Value = strOSPath & path
			addElement.Properties.Item("allowed").Value = True
			addElement.Properties.Item("description").Value = "ASP.NET v4.0.30319"
			addElement.Properties.Item("groupId").Value = "ASP.NET v4.0.30319"
			isapiCgiRestrictionCollection.AddElement(addElement)	
		End If
		found = 0	
	End If
	
	' Enable 32Bit App On Win64
	Set applicationPoolsSection = adminManager.GetAdminSection("system.applicationHost/applicationPools", "MACHINE/WEBROOT/APPHOST/")
	Set applicationPoolDefaultsElement = applicationPoolsSection.ChildElements.Item("applicationPoolDefaults")
	applicationPoolDefaultsElement.Properties.Item("enable32BitAppOnWin64").Value = True
	
	adminManager.CommitChanges()
	
	' Set Port Binding
	If GetIISPortBinding (strIISProtocol, strIISPort) <> "True" Then ResetIISPortBindings "Default Web Site", strIISProtocol, strIISPort
	
End Sub

Sub InstallSQL (p_SQLAdminGroup, p_SQLInstanceName, p_Feature, p_SQLVersionPath, p_SQLCollation)
	' This sub triggers the installation of the SQL server, depending on the bitness of the OS as determined by the script
	LogEvent "SQL Installation"
		
	If p_Feature <> "" Then
		LogEvent "Features : " & p_Feature
		p_Feature = " /FEATURES=" & p_Feature & " "
	End If
	
	If p_SQLCollation <> "" Then
		LogEvent "Collation : " & p_SQLCollation
		p_SQLCollation = " /SQLCOLLATION=" & p_SQLCollation & " "
	End If

	REM If strDisplayMode = "verbose" Then
		REM p_Feature = " /INDICATEPROGRESS "
	REM End If	
		
	strProcess = p_SQLVersionPath
	strParam = "/QS /Action=Install /SKIPRULES=RebootRequiredCheck /IAcceptSQLServerLicenseTerms /ENU /UpdateEnabled=False /Role=AllFeatures_WithDefaults " & p_Feature & p_SQLCollation & " /NPENABLED=1 /TCPENABLED=1 /BROWSERSVCSTARTUPTYPE=Automatic /ADDCURRENTUSERASSQLADMIN=True /InstanceName="""& p_SQLInstanceName & """ /SQLSYSADMINACCOUNTS=""" & p_SQLAdminGroup & """ """  & strSystemName & """ """ & FullLoginName(strSVCAccountName, strSVCLogonDomain) & """ /SQLSVCACCOUNT=""" & strSystemName & """"
	
	LogEvent "Installing SQL Server Express"
	LogEventHide "from " & p_SQLVersionPath, 1
	
	ExecuteProcess strProcess, strParam

	FindSQLLog strLogFolder	
	FindSQLTools

	LogEvent "Refresh Environment Path"

	refreshEnvPath

End Sub

Sub InstallSSMS (p_SSMSVersionPath, p_SQLVersionPath)
	' This sub triggers the installation of the SSMS
	LogEvent "SSMS Installation"
	
	If p_SSMSVersionPath = "" Then
	
		strProcess = p_SQLVersionPath
		strParam = "/QS /Action=Install /SKIPRULES=RebootRequiredCheck /IAcceptSQLServerLicenseTerms /ENU /UpdateEnabled=False /Role=AllFeatures_WithDefaults /FEATURES=SSMS"
	
	Else
		strSubLogFile = strLogFolder & "\SSMS\SQLSSMS.log"
		strProcess = p_SSMSVersionPath
		strParam = "/install /passive /norestart /log """ & strSubLogFile & """"
		
	End If

	LogEvent "Installing SQL Server Management Studio " & LCase(strOSArch)
	LogEvent "Please wait ..."
	
	ExecuteProcess strProcess, strParam

	LogEvent "... done"

	FindSQLTools	
	refreshEnvPath
	
	If p_SSMSVersionPath = "" Then
		FindSQLLog strLogFolder	
	REM Else
 		REM NextStep ("IS_InstallSQL")
	End If
	
End Sub

Sub UpgradeSSMS (p_SSMSVersionPath, p_SQLVersionPath)
	' This sub triggers the update of the SSMS
	LogEvent "SSMS update"

	If p_SSMSVersionPath = "" Then
	
		strProcess = p_SQLVersionPath
		strParam = "/QS /Action=Upgrade /SKIPRULES=RebootRequiredCheck /IAcceptSQLServerLicenseTerms /ENU /UpdateEnabled=False /FEATURES=SSMS /ISSVCACCOUNT=""NT AUTHORITY\NETWORK SERVICE"" "
	
		LogEvent "Installing SQL Server Management Studio " & LCase(strOSArch)
	
	Else
		strSubLogFile = strLogFolder & "\SSMS\SQLSSMS.log"
		strProcess = p_SSMSVersionPath
		strParam = "/install /passive /norestart /log """ & strSubLogFile & """"
		
	End If

	LogEvent "Upgrading SQL Server Management Studio " & LCase(strOSArch)
	
	ExecuteProcess strProcess, strParam

	FindSQLLog strLogFolder	
	FindSQLTools
	refreshEnvPath

End Sub

Sub UpgradeSQL (p_SQLInstanceName, p_SQLVersionPath)
	' This sub triggers the upgrade of the SQL server, depending on the bitness of the OS as determined by the script
	LogEvent "SQL Upgrade"
	
	strProcess = p_SQLVersionPath
	strParam = "/QS /Action=Upgrade /SKIPRULES=RebootRequiredCheck /IAcceptSQLServerLicenseTerms /ENU /UpdateEnabled=False /InstanceName="""& p_SQLInstanceName &""" /ISSVCACCOUNT=""NT AUTHORITY\NETWORK SERVICE"" "

	REM If strDisplayMode = "verbose" Then
		REM strParam = strParam & " /INDICATEPROGRESS "
	REM End If	
	
	LogEvent "Upgrading SQL Server Express"
	LogEventHide "from " & p_SQLVersionPath, 1
	
	ExecuteProcess strProcess, strParam

	FindSQLLog strLogFolder	
	FindSQLTools

	ExecuteProcess strProcess, strParam
	
	FindSQLTools
	refreshEnvPath

End Sub

Function FullLoginName(p_SVCAccountName, p_SVCLogonDomain)

	If p_SVCLogonDomain <> "local" Then
		FullLoginName = p_SVCLogonDomain & "\" & p_SVCAccountName
	Else
		FullLoginName = strComputer & "\" & p_SVCAccountName
	End If

End Function

Function FullLoginFlat(p_SVCAccountName, p_SVCLogonDomain)

	If p_SVCLogonDomain <> "local" Then	FullLoginFlat = LEFT(p_SVCLogonDomain,InStr(p_SVCLogonDomain, ".")-1) & "\" & p_SVCAccountName

End Function




Sub CreateServiceAccount (strSVCAccountName, strSVCAccountPwd)

	LogEvent "Local Account Creation"
	
	Dim colAccounts
	Dim objUserEx
	Dim objUser
	Dim objPasswordExpirationFlag
	Dim Group
	Dim intExists
	
	Set colAccounts = GetObject("WinNT://" & strComputer & ",computer")

	colAccounts.Filter = Array("user")
	For Each objUserEx In colAccounts
		If objUserEx.Name = strSVCAccountName Then
			intExists = 1
		End If
	Next
	
	If intExists <> 1 Then
	
		LogEvent "Creating local user: " & strSVCAccountName
		Set objUser = colAccounts.Create("user", strSVCAccountName)
	
		LogEvent "Setting password."
		objUser.SetPassword strSVCAccountPwd

		Const ADS_UF_DONT_EXPIRE_PASSWD = &h10000
		objPasswordExpirationFlag = ADS_UF_DONT_EXPIRE_PASSWD
		objUser.Put "userFlags", objPasswordExpirationFlag

		LogEvent "Setting password not to expire."
		objUser.SetInfo 

		LogEvent "Adding user to local administrators group."
		Set Group = GetObject("WinNT://" & strComputer & "/" & strAdministratorsCaption & ",group")
		Group.Add(objUser.ADspath)

	Else
		LogEvent "Account already exists"
	
	End If
	
	Set colAccounts = Nothing
	Set objUser = Nothing
	Set objUserEx = Nothing
	Set objPasswordExpirationFlag = Nothing
	Set Group = Nothing

	
End Sub

Function GetCurrentUser

	LogEvent "Get current User"
	
	Dim objNetwork

	Set objNetwork = CreateObject("Wscript.Network")
	GetCurrentUser = objNetwork.UserName
	LogEvent "Current User " & objNetwork.UserName

End Function

Function GetCurrentUserDomain

	LogEvent "Get current User Domain"
	
	Dim objSysInfo

	Set objSysInfo = CreateObject( "WinNTSystemInfo" )
	GetCurrentUserDomain = objSysInfo.DomainName
	WScript.Echo "Current User Domain: " & objSysInfo.DomainName

End Function

Sub FillDatabase (strSQLFullInstanceName, strDatabase, strSQLServerUser, strSQLServerPass, ByVal strCreateSQLUser)
	
	CreateSQLTables strSQLFullInstanceName, strDatabase, strSQLServerUser, strSQLServerPass
	
	LogEvent "Create Domain setting"
	
	' Create and enable ManageSoft Domain
	ExecSQLQuery strSQLFullInstanceName, strDatabase, strSQLServerUser, strSQLServerPass, "IF NOT (SELECT COUNT(OrganizationID) FROM Domain WHERE DN='DC=MANAGESOFT') > 0 EXEC DomainCreate 'DC=MANAGESOFT', 'MGS'", "DomainCreateManageSoft"
	ExecSQLQuery strSQLFullInstanceName, strDatabase, strSQLServerUser, strSQLServerPass, "UPDATE Domain Set FlatName = 'MANAGESOFT' WHERE DN='DC=MANAGESOFT'", "FlatNameManageSoft"
	ExecSQLQuery strSQLFullInstanceName, strDatabase, strSQLServerUser, strSQLServerPass, "UPDATE DomainConfiguration Set Value = 1 WHERE DomainID = (SELECT OrganizationID FROM Domain WHERE DN='DC=MANAGESOFT') AND (Property = 'ADReconcile' OR Property = 'MergeComputers' OR Property = 'MergePolicies' OR Property = 'MergeUsers');", "DomainConfigurationManageSoft"

	' Ensure DB Access and Membership for SQL User
	IF strSQLServerAuth = "WindowsNT" THEN strCreateSQLUser = FullLoginFlat(strCreateSQLUser, strSVCLogonDomain)
	ExecSQLQuery strSQLFullInstanceName, strDatabase, strSQLServerUser, strSQLServerPass, "EXEC sp_addrolemember 'mgs_writer', '" & strCreateSQLUser & "'", "sp_addrolemember_mgs_writer"
	ExecSQLQuery strSQLFullInstanceName, strDatabase, strSQLServerUser, strSQLServerPass, "EXEC sp_addrolemember 'mgs_reader', '" & strCreateSQLUser & "'", "sp_addrolemember_mgs_reader"

	
	Exit Sub
End Sub

Sub CreateSQLTables (strSQLFullInstanceName, strDatabase, strSQLServerUser, strSQLServerPass)

	LogEvent "Create SQL Tables"
	
	' Create on separately SQL all necessary tables
	ExecSQLFile strSQLFullInstanceName, strDatabase, strSQLServerUser, strSQLServerPass, strPath & "Server\Migration\Database Migration\Creation\schema.sql", "DatabaseCreationSchema.sql"
	ExecSQLFile strSQLFullInstanceName, strDatabase, strSQLServerUser, strSQLServerPass, strPath & "Server\Migration\Database Migration\Creation\OpQueries.sql", "DatabaseCreationOpQueries.sql"
	ExecSQLFile strSQLFullInstanceName, strDatabase, strSQLServerUser, strSQLServerPass, strPath & "Server\Migration\Database Migration\Creation\OpJobs.sql", "DatabaseCreationOpJobs.sql"
	ExecSQLFile strSQLFullInstanceName, strDatabase, strSQLServerUser, strSQLServerPass, strPath & "Server\Migration\Database Migration\Creation\mgsDropProcedures.sql", "DatabaseCreationMgsDropProcedures.sql"
	ExecSQLFile strSQLFullInstanceName, strDatabase, strSQLServerUser, strSQLServerPass, strPath & "Server\Migration\Database Migration\Creation\mgsProcedures.sql", "DatabaseCreationMgsProcedures.sql"
	ExecSQLFile strSQLFullInstanceName, strDatabase, strSQLServerUser, strSQLServerPass, strPath & "Server\Migration\Database Migration\Creation\perms.sql", "DatabaseCreationPerms.sql"

End Sub


Sub CreateSQLDB  (strSQLFullInstanceName, strDatabase, strSQLServerUser, strSQLServerPass)

	LogEvent "Create " & strDatabase & " database"

	ExecSQLQuery strSQLFullInstanceName, "Master", strSQLServerUser, strSQLServerPass, "IF NOT EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE ('[' + name + ']' = '" & strDatabase & "' OR name = '" & strDatabase & "')) CREATE DATABASE " & strDatabase, "CreateDatabase"

End Sub

Sub CreateSQLUser (strSQLFullInstanceName, strDatabase, strSQLServerUser, strSQLServerPass, ByVal strCreateSQLUser, strCreateSQLPass)

	IF strSQLServerAuth = "WindowsNT" THEN 
		strCreateSQLUser = FullLoginFlat(strCreateSQLUser, strSVCLogonDomain)
		ExecSQLQuery strSQLFullInstanceName, "Master", strSQLServerUser, strSQLServerPass, "IF NOT EXISTS (SELECT loginname FROM master.dbo.syslogins WHERE name = N'" & strCreateSQLUser & "') CREATE LOGIN [" & strCreateSQLUser & "] FROM WINDOWS", "CreateLogin"
	ELSE
		ExecSQLQuery strSQLFullInstanceName, "Master", strSQLServerUser, strSQLServerPass, "IF NOT EXISTS (SELECT loginname FROM master.dbo.syslogins WHERE name = N'" & strCreateSQLUser & "') CREATE LOGIN " & strCreateSQLUser & " WITH PASSWORD ='" & strCreateSQLPass & "'", "CreateLogin"
	END IF

	LogEvent "SQL Login for " & strCreateSQLUser & " created."
	LogEvent "Auth Type: " & strSQLServerAuth

	ExecSQLQuery strSQLFullInstanceName, strDatabase, strSQLServerUser, strSQLServerPass, "CREATE USER [" & strCreateSQLUser & "] WITH DEFAULT_SCHEMA=dbo", "CreateUser"
	ExecSQLQuery strSQLFullInstanceName, strDatabase, strSQLServerUser, strSQLServerPass, "EXEC sp_addrolemember db_owner, [" & strCreateSQLUser & "]", "sp_addrolemember db_owner"

	LogEvent "Permissions Set for " & strCreateSQLUser

	
End Sub

Function SetSSRSserverURL (p_SQLInstallMode)

	IF p_SQLInstallMode = "none" Or p_SQLInstallMode = "ssms"  THEN
		IF isBlank(strSQLInstanceName) THEN
			SetSSRSserverURL =  "http://" & strSQLServerName & "/Reportserver"
		ELSE
			SetSSRSserverURL = "http://" & strSQLServerName & "/Reportserver_" & strSQLInstanceName
		END IF
	ELSEIF p_SQLInstallMode = "install" Or p_SQLInstallMode = "upgrade" Or p_SQLInstallMode = "refresh" THEN
		IF strReplaceIP = "false" Then
			SetSSRSserverURL = "http://" & strComputer & "/Reportserver_" & strSQLInstanceName
		ELSE
			SetSSRSserverURL = "http://" & strIP & "/Reportserver_" & strSQLInstanceName
		END IF
	END IF
	
End Function


Function SetSQLInstanceName (p_SQLInstallMode)

	If p_SQLInstallMode = "none" Or p_SQLInstallMode = "ssms" Then
		If isBlank(strSQLInstanceName) Then
			SetSQLInstanceName = strSQLServerName
		Else
			SetSQLInstanceName = strSQLServerName & "\" & strSQLInstanceName
		End If
		If Len(strSQLServerPort) <> 0 Then SetSQLInstanceName = SetSQLInstanceName & "," & strSQLServerPort
	ElseIf p_SQLInstallMode = "install" Then
		SetSQLInstanceName = strComputer & "\" & strSQLInstanceName
	ElseIf  p_SQLInstallMode = "upgrade" Or p_SQLInstallMode = "refresh" Then
		Dim ConnectionStringSplit
		ConnectionStringSplit = Split(getDatabaseConnectionString(), ";" )
		SetSQLInstanceName = Replace(ConnectionStringSplit(1),"Server=", "")
	End If
	
End Function


Sub InstallRV (strInstallPath, strSVCAccountName, strSVCAccountPwd, strMGSDatabase, strComputer, strSQLFullInstanceName, strSQLServerUser, strSQLServerPass, p_customMST)
	
	LogEvent "Installing RayVentory"
	strSubLogFile = strLogFolder & "\AS_RV_Setup.log"
	
	strProcess = strOSPath & "\system32\msiexec.exe"
	strParam = "/i """ & strPath & "Server\Administration Server\ManageSoft for administration servers.Msi""" & _
	" /L*v """ & strSubLogFile & """" &_
	" " & strUILevelMSI &_
	" INSTALLDIR=""" & strInstallPath & """" & _
	" TRANSFORMS=""" & strPath & "Utils\Config\RayVentory.mst""" & _
	" ALLUSERS=1" & _
	" SCHEDUSERNAME=" & FullLoginName(strSVCAccountName, strSVCLogonDomain) & _
	" SCHEDPASSWORD=" & strSVCAccountPwd & _
	" IMPORTWEBUSERNAME=" & FullLoginName(strSVCAccountName, strSVCLogonDomain) & _
	" IMPORTWEBPASSWORD=" & strSVCAccountPwd & _
	" MGSDATABASENAME=""" & strMGSDatabase & """" & _
	" SQLSERVERNAME=""" & strSQLFullInstanceName & """" & _
	" COMPUTERNAME=" & strComputer & _
	" SHORTDLCOMPUTERNAME=" & strComputer & _
	" DLCOMPUTERNAME=" & strComputer & _
	" WAREHOUSEDIR=" & strWarehousePath & _
	" REBOOT=ReallySuppress"
	
	If strSQLServerAuth = "SQLServer" _
	AND strSQLServerUser <> ""  _
	AND strSQLServerPass <> "" _
	Then 
		strParam = strParam &_
		" MGSDBUSERNAME=""" & strSQLServerUser  & """" &_
		" MGSDBPASSWORD=""" & strSQLServerPass & """" &_
		" MGSDBAUTHTYPE=""" & strSQLServerAuth & """" &_
		" SQLAUTHENTICATIONTYPE=""" & strSQLServerAuth & """" &_
		" SQLUSERNAME=""" & strSQLServerUser & """" &_
		" SQLPASSWORD=""" & strSQLServerPass & """"
	End If
	
	If p_customMST <> "" Then 
		strParam = strParam &_
		" TRANSFORMS=""" &  p_customMST & """"
	End If
	
	ExecuteProcess strProcess, strParam
	
	
	
	If getOSVersion(strOSVersion) = "6.0" Or  getOSVersion(strOSVersion) = "6.1" Or  getOSVersion(strOSVersion) = "6.2" Or getOSVersion(strOSVersion) = "6.3" Or getOSVersion(strOSVersion) = "10.0" Then
	
		'Run Console as Admin
		setAppCompatFlags strInstallPath & "\AdministrationServer.exe", "RUNASADMIN"
		
		'Remove Inventories from direct import
		Dim adminManager, appSettings, appSettingsCollection, i
		Set adminManager = CreateObject("Microsoft.ApplicationHost.WritableAdminManager")
		adminManager.CommitPath = "MACHINE/WEBROOT/APPHOST/Default Web Site/ManageSoftRL"
		Set appSettings = adminManager.GetAdminSection("appSettings", "MACHINE/WEBROOT/APPHOST/Default Web Site/ManageSoftRL")
		Set appSettingsCollection = appSettings.Collection
		If Not appSettingsCollection Is Nothing Then
			For i=0 to CInt(appSettingsCollection.count) -1
				If appSettingsCollection.Item(i).Properties.Item("key").Value = "ImportTypesProcessedDirectly" Then
					appSettingsCollection.Item(i).Properties.Item("value").Value = "logs, discovery, securityanalysis, systemstatus, usagedata, securityevent"
				End If
			Next
		adminManager.CommitChanges()
		End If
		Set appSettingsCollection = nothing
		Set appSettings = nothing
		Set adminManager = nothing
		
	End If
	
	'Enable database maintenance
	LogEventHide "Enable database maintenanceschedule task", 1
	strProcess = strOSPath & "\system32\schtasks.exe"
	strParam = "/Change /Enable /TN ""ManageSoft\Service the ManageSoft database"""

	ExecuteProcess strProcess, strParam
	
	If getOSVersion(strOSVersion) = "10.0" Then
		
		'Reset Duration / Change Type to Once / Keep Interval
		ExecutePSS strPath & "Utils\Tools\Set-ScheduledTask10.ps1", " -User " & FullLoginName(strSVCAccountName, strSVCLogonDomain) & " -Password " & strSVCAccountPwd		
		
		
		' Old
		REM strProcess = strOSPath & "\System32\WindowsPowershell\v1.0\powershell.exe"
		REM strParam = "-ExecutionPolicy Bypass -NoLogo -NoProfile -NonInteractive -Command ""& {Get-ScheduledTask -TaskPath \ManageSoft\ | ForEach {$Trigger = New-ScheduledTaskTrigger -Once -At " & FormatDateTime(DateAdd("n",2,Now()), vbLongTime) & " -RepetitionInterval (New-TimeSpan -Minutes 1);$Trigger.Repetition.Interval = $_.triggers.Repetition.Interval;Set-ScheduledTask -Taskname $_.TaskName -TaskPath $_.TaskPath -Trigger $Trigger -User " & FullLoginName(strSVCAccountName, strSVCLogonDomain) & " -Password " & strSVCAccountPwd & " }}"""
		
		REM ExecuteProcess strProcess, strParam
		
		REM 'Reset Tasks start
		REM strProcess = ""
		REM strParam = "cmd /C for /f ""tokens=1 delims=,"" %f in ('schtasks /TN ManageSoft\ /NH /query /fo csv') do (schtasks /CHANGE /ru " & FullLoginName(strSVCAccountName, strSVCLogonDomain) & " /rp " & strSVCAccountPwd & " /tn %f /st " & FormatDateTime(DateAdd("n",2,Now()), vbLongTime)  & " /sd " & FormatDateTime(Now, vbShortDate) & ")"
		REM strFolder = strOSPath & "\system32"
		REM ExecuteProcessPath strProcess, strParam, strFolder, 0, 0
	
	End If
	
	'ExecSQLQuery strSQLFullInstanceName, strMGSDatabase, strSQLServerUser, strSQLServerPass, "DECLARE @GroupID AS int = (SELECT TOP 1 GroupID FROM [GROUP] WHERE GroupCN='MGS Administrators' ORDER BY GroupID DESC); EXEC RightSetAdminRightsByGroupID @GroupID"
	
	SetRVMessaging strActiveMQ
	
End Sub

Sub InstallDS (p_InstallPath, p_WarehousePath, p_Computer, p_JobParent, p_JobProtocol, p_ImportParent, p_ImportParentSQL, p_ImportUser , p_ImportPass, p_ImportTypes, p_customMST)
	Dim ADDLOCAL
	
	' Features Settungs 10.6
	' Distribution Server	ActiveMQ					-	Enables Active MQ
	'						dist						- 	Features Parent (ManageSoft for distribution servers)
	'						   RemoteExecution			- 	Allows initiation of remote execution tasks on managed devices
	'						   etd						-	Core Feature
	' 						   Gatherers				-	Feature Parent (Distribution server importers)
	'						      DiscoveryGatherer		-	Gathers discovery from distribution servers and places it into the ManageSoft database
	'						      EventLogProcessing	-	Event Log Processing loads XML files containing status events from managed devices and distribution servers into the ManageSoft database
	'						      Inventory				-	Inventory loads XML files containing inventory from managed devices and distribution servers into the ManageSoft database
	'						      SecurityAnalysis		-	Gathers the security analysis logs and places into the ManageSoft database (provided that Security Manager is installed)
	'						      SystemStatusGatherer	-	Gathers system status information from distribution servers and places it into the ManageSoft database
	'						      TaskStatusGatherer	-	Remote task status gatherer	Gathers remote task status information and places it into the ManageSoft database
	'						      Usage					- 	Gathers application usage data for applications installed and places it into the ManageSoft database
	' Managed Device		md 				-  	Features Parent (ManageSoft for managed devices)
	'						aua				- 	Application usage agent	Generates application usage data for applications installed on user's computers
	'						lnc				-	Installation agent	Installs ManageSoft packed applications, policies and schedules
	'						plc				-	Policy agent	Computes a resultant policy from user or machine policies
	'						sca				-	Schedule agent	Handles ManageSoft scheduled events
	'						securityagent	- 	Security agent	Monitors activity and applies ManageSoft security policy
	'						sel				-	Selection agent	Allows users to select optional software packages
	'						smc				-	SMS Integration	Extends Microsoft SMS with ManageSoft
	'						trk				-	Inventory agent	Generates hardware and software inventories of user's computers
	'						upl				-	Uploading agent	Uploads inventories and event logs to a server
	
	' Set Default Features without Managed Device
	ADDLOCAL = "dist,RemoteExecution,etd"
	
	'Enable ActiveMQ
	If strActiveMQ = "true" Then ADDLOCAL = ADDLOCAL & ",ActiveMQ"
	
	'Enable Managed Device
	If strInstallMD = "true" Then ADDLOCAL = ADDLOCAL & ",md,lnc,plc,sca,securityagent,sel,smc,trk,upl"
	
	LogEvent "Installing Distribution Server"
	strSubLogFile = strLogFolder & "\DS_Setup.log"
	
	strProcess = strOSPath & "\system32\msiexec.exe"
	strParam = "/i """ & strPath & "Server\Distribution server\Win32\ManageSoft for distribution servers.Msi""" & _
	" /L*v """ & strSubLogFile & """" &_
	"  " & strUILevelMSI &_
	" INSTALLDIR=""" & p_InstallPath & """" & _
	" ALLUSERS=1" & _
	" SCHEDUSERNAMEMODE=SYSTEM" &_
	" COMPUTERNAME=" & p_Computer & _
	" SHORTDLCOMPUTERNAME=" & p_Computer & _
	" DLCOMPUTERNAME=" & p_Computer & _
	" WAREHOUSEDIR=" & p_WarehousePath & _
	" STAGEDIR=" & p_WarehousePath & "\Staging" &_
	" STAGECOMMONDIR=" & p_WarehousePath & "\Staging\Common" & _
	" DEPLOYMENTDIR=Staging\Common" & _
	" CONFIGURE_NULLSESSION_SHARES=TRUE" & _ 
	" PROXY_SETTINGS=direct" & _ 
	" REBOOT=ReallySuppress"

	'" CONFIGIISFTP=FALSE" & _ 
	'" CONFIGUREIISFTP=FALSE" &_
	
	If p_JobParent <> "" _ 
	Then 
		strParam = strParam & _
		" DSJOBQLOCATION="  & p_JobParent & _
		" DSJOBQPROTOCOL=" & p_JobProtocol & _
		" DSJOBQREMOTE=True"
	End If
	
	If p_ImportParent <> ""	_
	Then 
		strParam = strParam &_
		" CORESERVERNAME=" & p_ImportParent &_
		" SQLSERVERDISPLAYNAME=" & p_ImportParentSQL &_
		" SetupType=Custom"
		
		ADDLOCAL = ADDLOCAL & ",Gatherers,DiscoveryGatherer,EventLogProcessing,Inventory,SecurityAnalysis,SystemStatusGatherer,TaskStatusGatherer,Usage"
		
		If p_ImportUser  <> "" _
		Then 
			strParam = strParam &_
			" IMPORTWEBUSERNAME=" & p_ImportUser & _
			" IMPORTWEBPASSWORD=" & p_ImportPass
		End If
	End If
	
	If ADDLOCAL <> "" _
	Then
		strParam = strParam &_
		" ADDLOCAL=" & ADDLOCAL
	End If
	
	If p_customMST <> "" _
	Then 
		strParam = strParam &_
		" TRANSFORMS=""" &  p_customMST & """"
	End If
			
	ExecuteProcess strProcess, strParam
	
	
	
	If getOSVersion(strOSVersion) = "6.0" _
	Or getOSVersion(strOSVersion) = "6.1" _ 
	Or getOSVersion(strOSVersion) = "6.2" _
	Or getOSVersion(strOSVersion) = "6.3" _ 
	Or getOSVersion(strOSVersion) = "10.0" _ 
	Then
	
		'Run Console as Admin
		setAppCompatFlags p_InstallPath & "\AdministrationServer.exe", "RUNASADMIN"
		
		If p_ImportTypes <> "" _
		Then 
			'Set direct processing
			LogEvent "Process import types directly: " & p_ImportTypes
			Dim adminManager, appSettings, appSettingsCollection, i
			Set adminManager = CreateObject("Microsoft.ApplicationHost.WritableAdminManager")
			adminManager.CommitPath = "MACHINE/WEBROOT/APPHOST/Default Web Site/ManageSoftRL"
			Set appSettings = adminManager.GetAdminSection("appSettings", "MACHINE/WEBROOT/APPHOST/Default Web Site/ManageSoftRL")
			Set appSettingsCollection = appSettings.Collection
			If Not appSettingsCollection Is Nothing Then
				For i=0 to CInt(appSettingsCollection.count) -1
					If appSettingsCollection.Item(i).Properties.Item("key").Value = "ImportTypesProcessedDirectly" Then
						appSettingsCollection.Item(i).Properties.Item("value").Value = p_ImportTypes '"logs, discovery, securityanalysis, systemstatus, usagedata, securityevent"
					End If
				Next
			adminManager.CommitChanges()
			End If
			Set appSettingsCollection = nothing
			Set appSettings = nothing
			Set adminManager = nothing
		End If
		
	End If
	
	SetRVMessaging strActiveMQ
	
End Sub


Sub InstallPortal
	LogEvent "Installing RayVentory Portal"
	strSubLogFile = strLogFolder & "\RayVentoryPortalSetup.log"
	
	strProcess = strOSPath & "\system32\msiexec.exe"
	strParam = "/i """ & strPath & "Portal\RayVentoryPortal.msi""" & _
	" INSTALLDIR=""" & strWarehousePath & """" & _
	" SVCACCOUNT=" & FullLoginName(strSVCAccountName, strSVCLogonDomain) & _
	" SVCPASSWORD=" & strSVCAccountPwd & _
	" PORTALSERVER=" & strComputer  & _
	" WEBSITE_PORT=" & strIISPort  & _
	" WEBSITE_ROOT=""Default Web Site""" & _
	" ALLUSERS=1" & _
	" REBOOT=ReallySuppress" & _
	"  " & strUILevelMSI & _
	" /L*v """ & strSubLogFile & """"
	
	' Protocol missing in setup
	'" WEBSITE_PROTOCOL="  & strIISProtocol  & _
	
	ExecuteProcess strProcess, strParam


	If getOSVersion(strOSVersion) = "6.0" Or  getOSVersion(strOSVersion) = "6.1" Or  getOSVersion(strOSVersion) = "6.2" Or getOSVersion(strOSVersion) = "6.3" Or getOSVersion(strOSVersion) = "10.0" Then
	
		'Folder Permission
		strProcess = strOSPath & "\system32\icacls.exe"
		strParam = strWarehousePath & " /inheritance:e"
		strFolder = strWarehousePath
		
		ExecuteProcessPath strProcess, strParam, strFolder, 0, 0

		'Set AppPool to Classic pipline mode
		Dim adminManager, applicationPools, applicationPoolsCollection, i
		Set adminManager = CreateObject("Microsoft.ApplicationHost.WritableAdminManager")
		adminManager.CommitPath = "MACHINE/WEBROOT/APPHOST"
		Set applicationPools = adminManager.GetAdminSection("system.applicationHost/applicationPools", "MACHINE/WEBROOT/APPHOST")
		Set applicationPoolsCollection = applicationPools.Collection
		If Not applicationPoolsCollection Is Nothing Then
			For i=0 to CInt(applicationPoolsCollection.count) -1
				If applicationPoolsCollection.Item(i).Properties.Item("name").Value = "RayVentory" Then
					applicationPoolsCollection.Item(i).Properties.Item("managedPipelineMode").Value = "Classic"
				End If
			Next
		adminManager.CommitChanges()
		End If
		Set applicationPoolsCollection = nothing
		Set applicationPools = nothing
		Set adminManager = nothing
		
	End If

	IISconfigureSection "system.webServer/security/authentication/anonymousAuthentication", "", "MACHINE/WEBROOT/APPHOST/Default Web Site/RayVentory", "enabled", false
	IISconfigureSection "system.webServer/security/authentication/windowsAuthentication", "", "MACHINE/WEBROOT/APPHOST/Default Web Site/RayVentory", "enabled", true
	
End Sub

Sub IISconfigureSection (p_section, p_cpath, p_path, p_item, p_value)

	Dim adminManager
	Dim IISconfigureSection
	
	If p_cpath = "" Then p_cpath = p_path
	
	LogEventHide "For IIS Section " & p_section & " Item " & p_item & " set to value " & p_value & " and commit in " & p_cpath, 1
		
	Set adminManager = CreateObject("Microsoft.ApplicationHost.WritableAdminManager")
	adminManager.CommitPath = p_cpath

	Set IISconfigureSection = adminManager.GetAdminSection(p_section, p_path)
	IISconfigureSection.Properties.Item(CStr(p_item)).Value = p_value

	adminManager.CommitChanges()
	
	Set IISconfigureSection = nothing
	Set adminManager = nothing
	
End Sub

'Get 32 Bit Program Files Folder for Installations
Function GetInstallPrgFiles32

	If strOSArch = "32-bit" Then
		GetInstallPrgFiles32 = GetEnvVariable ("ProgramFiles")
	Else
		GetInstallPrgFiles32 = GetEnvVariable ("ProgramFiles(x86)")
	End If
	
	If Len(strInstallDrive) = 1 Then
		GetInstallPrgFiles32 = Replace(GetInstallPrgFiles32, "C:", strInstallDrive & ":")
	End If

End Function


Sub InstallDNA
	LogEvent "Installing Comparex PCWSYSLive Service Client for DNA"
	strSubLogFile = strLogFolder & "\ComparexDNASetup.log"
	
	strProcess = strOSPath & "\system32\msiexec.exe"
	strParam = "/i """ & strPath & "Utils\Sources\installer\PCWSYSLiveServiceClient-Comparex.msi""" & _
	" TARGETDIR=""" & GetInstallPrgFiles32 & "\COMPAREX\PCWSYS Definition Live Service\""" & _
	" ALLUSERS=1" & _
	" REBOOT=ReallySuppress" & _
	" /qb-" & _
	" /L*v """ & strSubLogFile & """"
	
	ExecuteProcess strProcess, strParam

	
End Sub

Function EncryptString (p_String)
		strProcess = strInstallPath & "\DotNet\bin\mgsReportingPasswordEncryption.exe"
		strParam = "-p " & p_String
		strFolder = strInstallPath & "\DotNet\bin"
		
		EncryptString = ExecStdOut(strProcess, strParam, strFolder)
		
End Function


Sub InstallPrePatch (strInstallPath, strSVCAccountName, strSVCAccountPwd, strMGSDatabase, strComputer, strSQLFullInstanceName, strSQLServerUser, strSQLServerPass)
	' This sub installs RayVentory/RayManageSoft Preparation Patch
	Dim strFile
	Dim Return
	
	LogEvent "Installing Preparation Patch"
	strSubLogFile = strLogFolder & "\AS_RV_ServerPrePatch.log"
	
	strProcess = strOSPath & "\system32\msiexec.exe"
	strParam = "/p """ & strPath & "Server\Migration\Migration Preparation Patch\RMS_DM_PATCH_1646_PreparationPatch.msp""" & _
	" /L*v """ & strSubLogFile & """" &_
	"  " & strUILevelMSI &_
	" INSTALLDIR=""" & strInstallPath & """" & _
	" ALLUSERS=1" & _
	" SCHEDUSERNAME=" & FullLoginName(strSVCAccountName, strSVCLogonDomain) & _
	" SCHEDPASSWORD=" & strSVCAccountPwd & _
	" IMPORTWEBUSERNAME=" & FullLoginName(strSVCAccountName, strSVCLogonDomain) & _
	" IMPORTWEBPASSWORD=" & strSVCAccountPwd & _
	" MGSDATABASENAME=""" & strMGSDatabase & """" & _
	" SQLSERVERNAME=""" & strSQLFullInstanceName & """" & _
	" COMPUTERNAME=" & strComputer & _
	" SHORTDLCOMPUTERNAME=" & strComputer & _
	" DLCOMPUTERNAME=" & strComputer & _
	" WAREHOUSEDIR=" & strWarehousePath & _
	" REBOOT=ReallySuppress" & _
	" REINSTALL=ALL" &_
	" REINSTALLMODE=vomus"

	If strSQLServerAuth = "SQLServer" AND strSQLServerUser <> "" AND strSQLServerPass <> "" Then 
		strParam = strParam &_
		" MGSDBUSERNAME=""" & strSQLServerUser  & """" &_
		" MGSDBPASSWORD=""" & strSQLServerPass & """" &_
		" MGSDBAUTHTYPE=""" & strSQLServerAuth & """" &_
		" SQLAUTHENTICATIONTYPE=""" & strSQLServerAuth & """" &_
		" SQLUSERNAME=""" & strSQLServerUser & """" &_
		" SQLPASSWORD=""" & strSQLServerPass & """"
	End If

	
	ExecuteProcess strProcess, strParam

	
End Sub	

Sub DatabaseMigration (strSQLFullInstanceName, strMGSDatabase, strSQLServerUser, strSQLServerPass)
	' Migrate Database

	LogEvent "Database Migration"
	strSubLogFile = strLogFolder & "\AS_RV_ServerDatabaseMigration.log"
	
	strProcess = strPath & "Server\Migration\Database Migration\Migration\mgsDatabaseUpdate.exe"
	strParam = "-i """ & strPath & "Server\Migration\Database Migration\Migration\DeploymentManagerMigration.xml""" & _
	" -s """ & strSQLFullInstanceName & """ -d """& strMGSDatabase &""" -nsu" & _
	" -l """ & strSubLogFile & """"
	strFolder = strPath & "Server\Migration\Database Migration\Migration"

	If strSQLServerUser <> "" Then strParam = strParam & " -u " & strSQLServerUser
	If strSQLServerPass <> "" Then strParam = strParam & " -p " & strSQLServerPass
	
	ExecuteProcessPath strProcess, strParam, strFolder, 0, 0
	
	' Update database using creation scripts
	CreateSQLTables strSQLFullInstanceName, strMGSDatabase, strSQLServerUser, strSQLServerPass
	
End Sub		

Sub DatabaseMigrationPatch (strSQLFullInstanceName, strMGSDatabase, strSQLServerUser, strSQLServerPass)
	' Migrate Database
	
	LogEvent "Database Patch Migration"
	strSubLogFile = strLogFolder & "\AS_RV_ServerPatchDatabaseMigration.log"
	
	strProcess = strPath & "Server\Migration\Database Migration\Migration_Patch\mgsDatabaseUpdate.exe"
	strParam = "-i """ & strPath & "Server\Migration\Database Migration\Migration_Patch\DeploymentManagerMigration.xml""" & _
	" -s """ & strSQLFullInstanceName & """ -d """& strMGSDatabase &""" -nsu" & _
	" -l """ & strSubLogFile & """"
	strFolder = strPath & "Server\Migration\Database Migration\Migration_Patch"

	If strSQLServerUser <> "" Then strParam = strParam & " -u " & strSQLServerUser
	If strSQLServerPass <> "" Then strParam = strParam & " -p " & strSQLServerPass

	
	ExecuteProcessPath strProcess, strParam, strFolder, 0, 0
	
End Sub	
		
Sub ReplaceIPHierarchy (strComputer, strIP)
	' This sub replaces computer name with the IP address in the hierarchy

	LogEvent "Replacing server name with IP address in hierarchy"

	Dim objCFGFSO
	Dim objCFGFile
	Dim strText
	Dim strNewText

	Const ForReading = 1
	Const ForWriting = 2

	LogEventHide "Replacing hierarchy.cfg string " & strComputer & " with IP address " & strIP, 1

	Set objCFGFSO = CreateObject("Scripting.FileSystemObject")
	Set objCFGFile = objCFGFSO.OpenTextFile(strWarehousePath & "\Repository\DeploymentLocations\Common\hierarchy.cfg", ForReading)

	strText = objCFGFile.ReadAll
	objCFGFile.Close
	strNewText = Replace(strText, strComputer, strIP)

	Set objCFGFile = objCFGFSO.OpenTextFile(strWarehousePath & "\Repository\DeploymentLocations\Common\hierarchy.cfg", ForWriting)
	objCFGFile.WriteLine strNewText
	objCFGFile.Close

	LogEvent "Synchronizing Database and hierarchy.cfg"
	strProcess = strInstallPath & "\DotNet\bin\mgsmighier.exe"
	ExecuteProcess strProcess, ""

	Set objCFGFSO = Nothing
	Set objCFGFile = Nothing
	
End Sub

Sub ReplaceIPRegistry (strOSArch, strIP)
	' This sub replaces computer name with IP address in ActionShare, PublicToolsShare registry keys
	
	LogEvent "Replacing server name with IP in registry"
	
	Dim objReg
	Dim strKeyPath

	Const HKEY_LOCAL_MACHINE = &H80000002
	 
	Set objReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\default:StdRegProv")
	 
	If LCase(strOSArch) = "32-bit" Then
	strKeyPath = "SOFTWARE\ManageSoft Corp\ManageSoft\RemoteExecution\CurrentVersion"
	Else
	strKeyPath = "SOFTWARE\Wow6432Node\ManageSoft Corp\ManageSoft\RemoteExecution\CurrentVersion"
	End If

	LogEventHide "Adding IP address: HKLM\" & strKeyPath & "ActionShare: \\" & strIP & "\mgsREA$", 1 
	LogEventHide "Adding IP address: HKLM\" & strKeyPath & "PublicToolsShare: \\" & strIP & "\mgsRET$", 1
	
	objReg.SetStringValue HKEY_LOCAL_MACHINE,strKeyPath,"ActionShare","\\" & strIP & "\mgsREA$"
	objReg.SetStringValue HKEY_LOCAL_MACHINE,strKeyPath,"PublicToolsShare","\\" & strIP & "\mgsRET$"

	Set objReg = Nothing
	
End Sub 

Sub AddIPSSRSURL (strIP)
	'Add IP to SSRS URL
	ExecutePSS strPath & "Utils\Tools\rsconfigreserveURL.ps1", "-service ReportServerWebService -url http://" & strIP & ":80"
	ExecutePSS strPath & "Utils\Tools\rsconfigreserveURL.ps1", "-service ReportManager -url http://" & strIP & ":80"
	
End Sub

Sub DecompressAddon (p_source, p_target)
	' This sub decompresses Addons and Hotfixes

	LogEvent "Decompressing Addon"
	
	strProcess = strPath & "Utils\Tools\7za.exe"
	strParam = "x """ & p_source & """ -o""" & p_target & """ -y"
	ExecuteProcess strProcess, strParam

End Sub

Sub InstallOWC (strPath)
	LogEvent "Installing Office Web Controls"
	
	strProcess = strOSPath & "\system32\msiexec.exe"
	strParam = "/i """ & strPath & "Utils\Sources\installer\owc11.msi"" REBOOT=ReallySuppress " & strUILevelMSI
	
	ExecuteProcess strProcess, strParam
	
End Sub

Function GetCurrentJRE
	On Error Resume Next
	Dim oShell, oFSO, sFile, jre
	Set oShell = CreateObject("WScript.Shell")
	Set oFSO = CreateObject("Scripting.FileSystemObject")
	
	' Get Current Java
	LogEventHide "Searching for current Java Version", 1
	sFile = strProgramData & "\Oracle\Java\javapath\java.exe"
	jre = oFSO.GetFileVersion(sFile)
	If Not isBlank(jre) Then LogEventHide "Version found " & jre, 1

	GetCurrentJRE = jre
	On Error GoTo 0 
End Function

Sub InstallJRE (pPath)
	Dim jre
	jre = GetCurrentJRE
	If left(jre, 3) <> "8.0" _
	Then
		LogEvent "Installing Java Runtime"
		strSubLogFile = strLogFolder & "\JavaSetup.log"
		
		strProcess = strOSPath & "\system32\msiexec.exe"
		strParam = "/i """ & pPath & "Utils\Sources\installer\jre1.8.0_111.msi"" JU=0 JAVAUPDATE=0 AUTOUPDATECHECK=0 STATIC=0 RebootYesNo=No REBOOT=ReallySuppress WEB_JAVA=0 /q /L """ & strSubLogFile & """"	' Logging enabled 
		strFolder = pPath & "Utils"
	
		ExecuteProcessPath strProcess, strParam, strFolder, 0, 1
	Else
		LogEvent "Java Version " & jre & " already installed" 
	End If

End Sub

Sub Unlock (strAuth)
	LogEvent "Unlocking " & strAuth 
	
	'IISconfigureSection "system.webServer/security/authentication/" & strAuth & "", "", "MACHINE/WEBROOT/APPHOST/Default Web Site/ManageSoftRP", "OverrideMode", "Allow"
	
	strProcess = strOSPath & "\system32\inetsrv\appcmd.exe"
	strParam = "unlock config /section:" & strAuth
	
	ExecuteProcess strProcess, strParam
	
End Sub

Sub AuthManageSoftRP (strAuth, strBool)
	LogEvent "Setting " & strAuth & " to enabled: " & strBool 
	
	IISconfigureSection "system.webServer/security/authentication/" & strAuth & "", "", "MACHINE/WEBROOT/APPHOST/Default Web Site/ManageSoftRP", "enabled", strBool
	
End Sub

Sub CheckPrereqs (pOSVERSION)
	Dim longFiles, objReg, strKeyPath, dwNet35, dwNet4
	
	LogEvent "Checking setup directory."
	LogEvent "Looking for files/folders with abnormal long names."
	longFiles = checkFileFolderByLength(strPath, 260)
	
	If longFiles > 0 Then 
		LogEvent "Warning! " & longFiles & " files and folders found!"
		LogEvent "Hint: Move installation folder."
		Pause()
	Else
		LogEvent "Everything looks Ok. Nothing found"
	End If

	LogEvent "Checking if prerequisites are installed"
	
	'Check Powershell
	
	Const HKEY_LOCAL_MACHINE = &H80000002
	Set objReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\default:StdRegProv")	

	strKeyPath = "SOFTWARE\Microsoft\PowerShell\1"
	objReg.GetDWORDValue HKEY_LOCAL_MACHINE,strKeyPath, "Install", strPowerShell1

	strKeyPath = "SOFTWARE\Microsoft\PowerShell\3"
	objReg.GetDWORDValue HKEY_LOCAL_MACHINE,strKeyPath, "Install", strPowerShell3
	
	Set objReg = Nothing
	
	REM If isBlank(strPowerShell1) Then
		REM If pOSVERSION = "6.0" Then
			REM strProcess = "wusa.exe"
			
			REM LogEvent "Prerequisite PowerShell is missing. Try installing it..."
			REM LogEvent "This will require: KB968930"
			REM If LCase(strOSArch) = "32-bit" Then
				REM strParam = "/quiet /norestart " & strPath & "Utils\Sources\kb\2008\Windows6.0-KB968930-x86.msu"""
			REM Else
				REM strParam = "/quiet /norestart " & strPath & "Utils\Sources\kb\2008\Windows6.0-KB968930-x64.msu"""
			REM End If
			
			REM ExecuteProcess strProcess, strParam
		REM Else
			REM LogEvent "Prerequisite PowerShell is missing. Exiting..."
			REM ScriptQuit 1
		REM End If
	REM Else
		REM LogEvent "PowerShell 1: " & strPowerShell1
	REM End If	
	
	If Not isBlank(strPowerShell3) Then LogEvent "PowerShell 3: " & strPowerShell3

	setIEESC(0)

	LogEvent "Cleanup frozen installations"
	
	strProcess = strOSPath & "\system32\taskkill.exe"
	strParam = " /f /im msiexec.exe"
	
	ExecuteProcess strProcess, strParam
	
End Sub

Sub InstallNET (pOSVERSION)
	LogEvent "Checking .Net Installation"
	
	If pOSVERSION = "6.0" Then
		Dim longFiles, objReg, strKeyPath, dwNet35, dwNet4
		Const HKEY_LOCAL_MACHINE = &H80000002
		Set objReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\default:StdRegProv")	
		
		strKeyPath = "SOFTWARE\Microsoft\NET Framework Setup\NDP"

		objReg.GetDWORDValue HKEY_LOCAL_MACHINE,strKeyPath & "\v3.5", "Install", dwNet35
		objReg.GetDWORDValue HKEY_LOCAL_MACHINE,strKeyPath & "\v4\Full", "Install", dwNet4

		LogEvent ".NET 3.5 : " & dwNet35
		LogEvent ".NET 4.0 : " & dwNet4
		
		If isBlank(dwNet35) And pOSVERSION = "6.0" Then
			LogEvent "Prerequisite .NET 3.5 is missing. Try installing it..."
			LogEvent "This may require an internet connection."
			
			strProcess = "dotnetfx35.exe"
			strParam = "/qb /norestart"
			strFolder = strPath & "Utils\Sources\installer"
		
			ExecuteProcessPath strProcess, strParam, strFolder, 0, 0
		End If
		
		If isBlank(dwNet4) Then
			LogEvent "Prerequisite .NET 4.0 is missing. Try installing it..."
			strSubLogFile = strLogFolder &"\dotNetFx40.log"
			
			strProcess = "dotNetFx40_Full_x86_x64.exe"
			strParam = "/q /norestart /log """ & strSubLogFile & """"
			strFolder = strPath & "Utils\Sources\installer"
		
			ExecuteProcessPath strProcess, strParam, strFolder, 0, 0
		End If
	ElseIf pOSVERSION = "6.1" Or pOSVERSION = "6.2" Or pOSVERSION = "6.3" Or pOSVERSION = "10.0" Then
			LogEvent "Prerequisite Certificate for .NET 4.7"
			
			strProcess = "CertMgr.exe"
			strParam = "/add " & strPath & "Utils\Sources\installer\MicRooCerAut2011_2011_03_22.crt /s /r localMachine root"
			strFolder = strPath & "Utils\Tools"
		
			ExecuteProcessPath strProcess, strParam, strFolder, 0, 0
	
	
	
			LogEvent "Prerequisite .NET 4.7. Try installing it..."
			strSubLogFile = strLogFolder &"\dotNetFx47.log"
			
			strProcess = "NDP47-KB3186497-x86-x64-AllOS-ENU.exe"
			strParam = "/q /norestart /log """ & strSubLogFile & """"
			strFolder = strPath & "Utils\Sources\installer"
		
			ExecuteProcessPath strProcess, strParam, strFolder, 0, 0

	End If
	
End Sub

Sub ExecSQLFile (p_SQLFullInstanceName, p_Database, p_User, p_Password, p_File, p_output)
	Dim sqlcmdPath
	
	'Refresh current Path variable
	refreshEnvPath
	
	'SQLCMD folgder fallback
	If Not isBlank(strODBCToolsPath) Then
		sqlcmdPath = strODBCToolsPath
	ElseIf Not isBlank(strSQLToolsPath) Then
		sqlcmdPath = strSQLToolsPath
	ElseIf Not isBlank(strSQLToolsPath32) Then
		sqlcmdPath = strSQLToolsPath32
	Else
		sqlcmdPath = strFolder
	End If
	
	'Setup Parameter
	strProcess = "sqlcmd.exe"
	strParam = "-S " & p_SQLFullInstanceName & " -d " & p_Database & " -i """ & p_File & """"
	strFolder = sqlcmdPath
	
	'Check if user/password is set
	If strSQLServerAuth = "SQLServer" AND p_User <> "" AND p_Password <> "" Then 
		strParam = strParam & " -U " & p_User& " -P " & p_Password
	Else 
		strParam = strParam & " -E"
	End If
	
	'Check if Ouput is required
	If p_output <> "" Then
		
		Dim LogFolder, objLogFSO 
		LogFolder = strLogFolder & "\SQLCMD"
		strSubLogFile = LogFolder & "\" & p_output & ".log"
				
		strParam = strParam & " -o """ & strSubLogFile & """"
		
		'Create folder if required
		Set objLogFSO = CreateObject("Scripting.FileSystemObject")
		If Not (objLogFSO.FolderExists(LogFolder)) Then objLogFSO.CreateFolder(LogFolder)
		Set objLogFSO = Nothing
		
	End If
	
	'Call Procedure
	ExecuteProcessPath strProcess, strParam, strFolder, 0, 0

End Sub

Sub ExecSQLQuery (strSQLFullInstanceName, strDatabase, strUser, strPassword, strQuery, p_output)
	Dim sqlcmdPath
	
	'Refresh current Path variable
	refreshEnvPath
	
	'SQLCMD folgder fallback
	If Not isBlank(strODBCToolsPath) Then
		sqlcmdPath = strODBCToolsPath
	ElseIf Not isBlank(strSQLToolsPath) Then
		sqlcmdPath = strSQLToolsPath
	ElseIf Not isBlank(strSQLToolsPath32) Then
		sqlcmdPath = strSQLToolsPath32
	Else
		sqlcmdPath = strFolder
	End If
	
	'Procedure
	strProcess = "sqlcmd.exe"
	strParam = "-S " & strSQLFullInstanceName & " -d " & strDatabase & " -Q """ & strQuery & """"
	strFolder = sqlcmdPath
	
	If strSQLServerAuth = "SQLServer" AND strUser <> "" AND strPassword <> "" Then 
		strParam = strParam & " -U " & strUser& " -P " & strPassword
	Else 
		strParam = strParam & " -E"
	End If
	
		'Check if Ouput is required
	If p_output <> "" Then
		
		Dim LogFolder, objLogFSO 
		strSubLogFile = LogFolder & "\" & p_output & ".log" 
		
		LogFolder = strLogFolder & "\SQLCMD"
		strParam = strParam & " -o """ & strSubLogFile & """"
		
		'Create folder if required
		Set objLogFSO = CreateObject("Scripting.FileSystemObject")
		If Not (objLogFSO.FolderExists(LogFolder)) Then objLogFSO.CreateFolder(LogFolder)
		Set objLogFSO = Nothing
		
	End If
	
	ExecuteProcessPath strProcess, strParam, strFolder, 0, 0

End Sub


Sub FindSQLTools

	LogEvent "Searching for SQL Tools"

	strODBCToolsPath = FindSQLToolsPath("ODBCToolsPath")
	strSQLToolsPath = FindSQLToolsPath("Path")
	strSQLToolsPath32 = FindSQLToolsPath32("Path")
	
	If strODBCToolsPath <> "" Then LogEventHide "Found SQL ODBC Tools in : " & strODBCToolsPath, 1
	If strSQLToolsPath <> "" Then LogEventHide "Found SQL Bin Tools in : " & strSQLToolsPath, 1
	If strSQLToolsPath32 <> "" Then LogEventHide "Found SQL Bin Tools (32) in : " & strSQLToolsPath32, 1
	
End Sub

Function FindSQLToolsPath32 (p_path)

	Dim OSArch, i
		
	OSArch = 64
	If LCase(strOSArch) = "32-bit" Then OSArch = 32
		
	For i = 130 To 90 Step -10
		If isBlank(FindSQLToolsPath32) Then FindSQLToolsPath32 = ReadRegStr(HKLM, "SOFTWARE\Microsoft\Microsoft SQL Server\" & i & "\Tools\ClientSetup", p_path, 32)
	Next
	
	'Fallback if path not found
	If isBlank(FindSQLToolsPath32) Then FindSQLToolsPath32 = strDefaultPath

End Function

Function FindSQLToolsPath (p_path)
	Dim OSArch, i
		
	OSArch = 64
	If LCase(strOSArch) = "32-bit" Then OSArch = 32
		
	For i = 130 To 90 Step -10
		If isBlank(FindSQLToolsPath) Then FindSQLToolsPath = ReadRegStr(HKLM, "SOFTWARE\Microsoft\Microsoft SQL Server\" & i & "\Tools\ClientSetup", p_path, OSArch)
	Next
	
	'Fallback if path not found
	If isBlank(FindSQLToolsPath) Then FindSQLToolsPath = strDefaultPath
	
End Function

Sub FindSQLLog (p_path)
	Const WindowsFolder = 0
	Const SystemFolder = 1
	Const TemporaryFolder = 2
	Dim BootstrapDir, TempFolderUser, TempFolderWindows, objFSO, OSArch, i
	
	Set objFSO = CreateObject("Scripting.FileSystemObject")
	TempFolderUser = objFSO.GetSpecialFolder(TemporaryFolder)
	TempFolderWindows = objFSO.GetSpecialFolder(WindowsFolder) & "\Temp"
	
	OSArch = 64
	If LCase(strOSArch) = "32-bit" Then OSArch = 32
		
	For i = 130 To 90 Step -10
		If isBlank(BootstrapDir) Then BootstrapDir = ReadRegStr(HKLM, "SOFTWARE\Microsoft\Microsoft SQL Server\" & i & "\Bootstrap", "BootstrapDir", OSArch)
	Next
	
	'Link SQL Log Dir
	LogEvent "Searching for SQL Log"
	LogEventHide "In :" & BootstrapDir & "Log", 1
	If objFSO.FolderExists(BootstrapDir & "Log") Then
		LogEventHide "Link " & p_path & "\SQLLog to """ & BootstrapDir & "Log""", 1
		CreateSymbolicLink BootstrapDir & "Log", p_path & "\SQLLog"
	End If
	
	'Copy SQL Setup Log from User Temp
	strSubLogFile = TempFolderUser & "\SqlSetup.log"
	LogEvent strSubLogFile
	If objFSO.FileExists(strSubLogFile) Then
		LogEventHide "Copy " & strSubLogFile & " to " & p_path, 1
		objFSO.CopyFile strSubLogFile, p_path & "\", True
	End If

	'Copy SQL Setup Log from User Temp
	strSubLogFile = TempFolderWindows & "\SqlSetup.log"
	LogEvent strSubLogFile
	If objFSO.FileExists(strSubLogFile) Then
		LogEventHide "Copy " & strSubLogFile & " to " & p_path, 1
		objFSO.CopyFile strSubLogFile, p_path & "\", True
	End If	

End Sub

Function CheckHotfixes(p_HotFixesID)
	Dim i, hfstatus, hfcount
	hfcount = 0
	
	If IsArray(p_HotFixesID) Then
		If UBound(p_HotFixesID) >= 0 Then
		For i = 0 To ubound(p_HotFixesID)
		hfstatus = CheckHotfix(p_HotFixesID(i)) 
		If hfstatus = true then 
			LogEvent "The hotfix KB" & p_HotFixesID(i) & " is installed." 
		Elseif hfstatus = false Then 
			LogEvent "The hotfix KB" & p_HotFixesID(i) & " is not installed." 
			LogEvent "Will try to install it." 
			
			strProcess = "wusa.exe"
			strParam = "/quiet /norestart " & strHotFixPath & p_HotFixesID(i)
			If LCase(strOSArch) = "32-bit" Then
				strParam = strParam & "-x86.msu"
			Else
				strParam = strParam & "-x64.msu"
			End If
			
			ExecuteProcessPath strProcess, strParam, strFolder, 0, 1
			hfcount = hfcount + 1

		Else  
			'Error 
			LogEvent "Error, unable to check for hotfix. Error is: " & status 
		End If 
		Next

		End If
	End If

	CheckHotfixes = hfcount
End Function

Function CheckHotfix(p_HotfixID) 
	Dim objWMIService, strWMIforesp, colQuickFixes, tal
	On Error Resume Next
    Set objWMIService = GetObject("winmgmts:" _ 
        & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") 
    if err.number <> 0 then 
        CheckHotfix = "WMI could not connect to computer '" & strPuter & "'" 
        exit function 'No reason to continue 
    end if 
     
	LogEventHide "The hotfix ID " & p_HotfixID & "..." ,1
    strWMIforesp = "Select * from Win32_QuickFixEngineering where HotFixID = 'Q" & p_HotfixID &_  
    "' OR HotFixID = 'KB" & p_HotfixID & "'" 
    Set colQuickFixes = objWMIService.ExecQuery (strWMIforesp) 
    if err.number <> 0 Then    'if an error occurs 
        CheckHotfix = "Unable to get WMI hotfix info" 
    else 'Error number 0 meaning no error occured  
        tal = colQuickFixes.count 
        if tal > 0 then 
            CheckHotfix = True
			LogEventHide ".. is not required", 1
        else  
            CheckHotfix = False
			LogEventHide ".. is required", 1
        end If 
    end if 
    Set colQuickFixes = Nothing 
     
    Err.Clear 
    On Error GoTo 0 
end function 

'Create a Symbolic Link for Folders
Sub CreateSymbolicLink(target, link)
    Dim strCommand
	Dim rc
	Dim objFSO
	Dim objShell

	Set objFSO = CreateObject("Scripting.FileSystemObject")
	Set objShell = CreateObject("WScript.Shell")


    strCommand = "%comspec% /c mklink /d """ & link & """ """ & target & """"
	
	If Not objFSO.FolderExists(target) Then
		LogEvent "Target " & target & " does not exist"
	ElseIf objFSO.FolderExists(link) Then
		LogEvent "Link " & link & " already exist"
	Else
		LogEventHide strCommand, 1
		If strDisplayMode = "verbose" Then
			rc = objShell.Run(strCommand, 1, True)
		Else
			rc = objShell.Run(strCommand, 0, True)
		End If
	End If
	
	If rc <> 0 And rc <> 128 And rc <> 3010 Then
		LogEvent "! Process exiting with status " & rc
		LogEvent "! Aborting..."
		ScriptQuit rc
	Else
		LogEventHide "CreateSymbolicLink successful", 1
	End If

	Set rc = Nothing
	Set objShell = Nothing
	Set objFSO = Nothing

End Sub

'Get ETAP install dir
Private Function getEtapInstallDir()

	getEtapInstallDir = ReadRegStr (HKLM, "SOFTWARE\ManageSoft Corp\ManageSoft", "ETAPInstallDir", 32) 
	If getEtapInstallDir <> "" Then getEtapInstallDir = Left(getEtapInstallDir, Len(getEtapInstallDir) - 1) End If
	
End Function

'Get Install dir
Private Function getInstallDir()

	getInstallDir = ReadRegStr (HKLM, "SOFTWARE\ManageSoft Corp\ManageSoft", "InstallDir", 32) 
	If getInstallDir <> "" Then getInstallDir = Left(getInstallDir, Len(getInstallDir) - 1) End If
	
End Function

'Get DatabaseConnectionString
Private Function getDatabaseConnectionString()

	getDatabaseConnectionString = ReadRegStr (HKLM, "SOFTWARE\ManageSoft Corp\ManageSoft\Reporter\CurrentVersion", "DatabaseConnectionString", 32) 
		
End Function


'Get ETAP install version
Private Function getEtapInstallVersion()

	getEtapInstallVersion = ReadRegStr (HKLM, "SOFTWARE\ManageSoft Corp\ManageSoft", "ETAPVersion", 32) 
	
End Function


'Get Repository Location
Private Function getRepoLoc()

	getRepoLoc = ReadRegStr (HKLM, "SOFTWARE\ManageSoft Corp\ManageSoft\Repository\CurrentVersion", "RepositoryLocation", 32) 
	
End Function


'Get Warehouse Location
Private Function getWarehouse()

	If not isBlank(getRepoLoc()) Then 
		getWarehouse = replace(getRepoLoc(),"\Repository","")
	Else
		getWarehouse = ""
	End If
	
End Function


'Set SSRS Location for RMS
Sub SetRMSSSRSLocation (p_ServerLocation, p_ServerDomainUserName, p_UserPassword)

	
	LogEvent "Set SSRS Location for RayVentory/RayManageSoft Server" 
	LogEventHide "Setup URL " & p_ServerLocation & " with User " & p_ServerDomainUserName, 1
	
	WriteRegStr HKLM, "SOFTWARE\ManageSoft Corp\ManageSoft\Reporter\CurrentVersion", "ServerLocation", p_ServerLocation, 32
	WriteRegStr HKLM, "SOFTWARE\ManageSoft Corp\ManageSoft\Reporter\CurrentVersion", "ServerDomainUserName", p_ServerDomainUserName, 32
	WriteRegStr HKLM, "SOFTWARE\ManageSoft Corp\ManageSoft\Reporter\CurrentVersion", "UserPassword", EncryptString(p_UserPassword), 32
	
End Sub

'Set Compatiblity Flagse
Sub setAppCompatFlags (p_application, p_flag)

	
	LogEvent "Set Application Compatiblity" 
	
	' Fix 2012R2 - Not required anymore
	'If getOSVersion(pOSVERSION) = "6.3" Then p_flag = "~ " & p_flag
	
	LogEventHide "Set " & p_flag & " for " & p_application, 1
		
	If LCase(strOSArch) = "32-bit" Then
		WriteRegStr HKLM, "SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers", p_application, p_flag, 32
		WriteRegStr HKCU, "SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers", p_application, p_flag, 32
	Else
		WriteRegStr HKLM, "SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers", p_application, p_flag, 64
		WriteRegStr HKCU, "SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers", p_application, p_flag, 64
	End If

End Sub

'Set IE Enhanced Security Configuration
REM Rundll32 iesetup.dll, IEHardenLMSettings
REM Rundll32 iesetup.dll, IEHardenAdmin
REM Rundll32 iesetup.dll, IEHardenUser

Sub setIEESC (p_flag)
	LogEvent "Set Application Compatiblity" 
	LogEventHide "Set " & p_flag & " for IEESC", 1
	
	'IEHardenAdmin
	If LCase(strOSArch) = "32-bit" Then
		WriteRegStr HKLM, "SOFTWARE\Microsoft\Active Setup\Installed Components\{A509B1A7-37EF-4b3f-8CFC-4F3A74704073}", "IsInstalled", p_flag, 32
	Else
		WriteRegStr HKLM, "SOFTWARE\Microsoft\Active Setup\Installed Components\{A509B1A7-37EF-4b3f-8CFC-4F3A74704073}", "IsInstalled", p_flag, 64
	End If

	'IEHardenUser
	If LCase(strOSArch) = "32-bit" Then
		WriteRegStr HKLM, "SOFTWARE\Microsoft\Active Setup\Installed Components\{A509B1A8-37EF-4b3f-8CFC-4F3A74704073}", "IsInstalled", p_flag, 32
	Else
		WriteRegStr HKLM, "SOFTWARE\Microsoft\Active Setup\Installed Components\{A509B1A8-37EF-4b3f-8CFC-4F3A74704073}", "IsInstalled", p_flag, 64
	End If
	
	
End Sub

Function RegKeyExists(p_RootKey, p_KeyPath, p_Key)

    
	    Set oCtx = CreateObject("WbemScripting.SWbemNamedValueSet")
    oCtx.Add "__ProviderArchitecture", RegType
	
	
	Dim oReg: S
	
	et oReg = GetObject("winmgmts:!root/default:StdRegProv")
    
	If oReg.EnumKey(p_RootKey & p_Key, p_KeyPath, arrSubKeys) = 0 Then
        KeyExists = True
    Else
        KeyExists = False
   End If
   
End Function


Sub VMWareReport
	' Register VMWareReports
	
	LogEvent "VMWareReport will be registered"
	
	strProcess = strPath & "Utils\VMware Reports\deploy.cmd"
	
	ExecuteProcess strProcess, ""
	
End Sub

Sub OSWReport
	' Register OSW
	
	LogEvent "Oracle Server Worksheet will be registered"
	
	strProcess = strPath & "Utils\Oracle Worksheet\deploy.cmd"
	
	ExecuteProcess strProcess, ""
	
End Sub

Sub CopyFolder (p_source, p_target, p_overwrite)
	' Copy Folders
	
	LogEventHide "Copy Folder " + p_source + " to " + p_target, 1
	
	Dim objFSO
	Set objFSO = CreateObject("Scripting.FileSystemObject")
	If objFSO.FolderExists(p_source) Then 
		objFSO.CopyFolder p_source, p_target , p_overwrite
		
	Else
		LogEvent "----------------------------------------------------------"
		LogEvent "Error: Folder " + p_source + " does not exist "
		LogEvent "----------------------------------------------------------"
		LogEvent ""
	End If 
	
End Sub

Sub Addons
	' Try remove alternate datastreams from install path
	If strPowerShell3 = 1 Then
		LogEventHide "Try to remove Zone.Identifier stream for all executables", 1
		ExecutePSS strPath & "Utils\Tools\clearADS.ps1", "-path """ & strInstallPath & """ -filter *.exe -stream Zone.Identifier"
		
		LogEventHide "Remove Zone.Identifier stream for all dlls", 1
		ExecutePSS strPath & "Utils\Tools\clearADS.ps1", "-path """ & strInstallPath & """ -filter *.dll -stream Zone.Identifier"
	End If


	' Use SMB share (default) instead coping files
	LogEvent "Enable Agentless by share"
	WriteRegStr HKLM, "SOFTWARE\ManageSoft Corp\ManageSoft\RemoteExecution\CurrentVersion", "UseShare", "True", 32

	' Use Primary DNS for discovery
	LogEvent "Enable Primary DNS for discovery"
	WriteRegStr HKLM, "SOFTWARE\ManageSoft Corp\ManageSoft\Discovery\CurrentVersion", "ExplicitDNS", "True", 32	
	
End Sub

Sub AddonsAS (strSQLFullInstanceName, strMGSDatabase, strSQLServerUser, strSQLServerPass)

	LogEvent "Addon Installation"
	
	LogEventHide "Run nddlm in case of new packages", 1
	strProcess = "nddlm.exe"
	strParam = ""
	strFolder = strInstallPath & "\Common"
		
	ExecuteProcessPath strProcess, strParam, strFolder, 0, 0
	
	
	' Disable Autoclose for all User database
	LogEventHide "Disable Autoclose", 1
	ExecSQLQuery strSQLFullInstanceName, "Master", strSQLServerUser, strSQLServerPass, "EXEC sp_MSforeachdb 'IF ''?'' NOT IN (''master'', ''model'', ''msdb'', ''tempdb'')  BEGIN PRINT ''?'' USE ? ALTER DATABASE CURRENT SET AUTO_CLOSE OFF END'", "Autoclose"
	
	'Run SQL Files in file order
	LogEvent "Run SQL"
	
	ReDim fileArray(-1)
	Dim element
	Dim folder

	folder = strPath & "Utils\Addon\SQL"

	For Each element in getFilesFromFolder(folder, "sql")
	
		LogEventHide "Source : " & folder & "\" & element, 1
		
		ExecSQLFile strSQLFullInstanceName, strMGSDatabase, strSQLServerUser, strSQLServerPass, folder & "\" & element, element

		If Err.Number = 0 Then
			ReDim Preserve fileArray(UBound(fileArray) + 1)
			fileArray(UBound(fileArray)) = (UCase(Left(element, 1)) &  Mid(element, 2))
		End If
		
	Next


End Sub

Function GetLocalGroupName (strSID)
	Dim objWMIService
	Dim colAccounts
	Dim objAccount
	Dim objSid

	Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

	Set objSid = objWMIService.Get ("Win32_SID.SID='" & strSID & "'")	
	GetLocalGroupName = objSid.ReferencedDomainName & "\" & objSid.AccountName
	
	
	If GetLocalGroupName = "" Then
		LogEvent "Cannot determine local name for SID " & strSID
		LogEvent "Exiting..."
		ScriptQuit 1
	End If
	
	Set objWMIService = Nothing
	Set colAccounts = Nothing
	Set objAccount = Nothing

End Function

Function GetLocalGroupCaption (strSID)
	Dim objWMIService
	Dim colAccounts
	Dim objAccount
	Dim objSid

	Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

	Set colAccounts = objWMIService.ExecQuery _
		("Select * From Win32_Group Where LocalAccount = TRUE And SID = '" & strSID & "'")

	For Each objAccount In colAccounts
		GetLocalGroupCaption = objAccount.Name
	Next
	
	If GetLocalGroupCaption = "" Then
		LogEvent "Cannot determine local caption for SID " & strSID
		LogEvent "Exiting..."
		ScriptQuit 1
	End If
	
	Set objWMIService = Nothing
	Set colAccounts = Nothing
	Set objAccount = Nothing

End Function

Function GetServiceState (p_serviceName)
	Dim objWMIService
	Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
	
	GetServiceState = objWMIService.Get("Win32_Service.Name='" & p_serviceName & "'").State

End Function

Sub SetServiceState (p_serviceName, p_serviceState)
' Check if service is "stopped" or "started". If not stop or start service

	Dim objWMIService, cServices, oService
	Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
	Set cServices = objWMIService.ExecQuery("SELECT * FROM Win32_Service")
	
	For Each oService In cServices
		If LCase(oService.Name) = LCase(p_serviceName) Then
			If oService.State <> p_serviceState Then
				If p_serviceState = "Stopped" Then oService.StopService()    
				If p_serviceState = "Started" Then oService.StartService()  
				LogEventHide "Service " & p_serviceName & " is now " & p_serviceState, 1
			Else
				LogEventHide "Service " & p_serviceName & " was already " & p_serviceState, 1
			End If
		End If  
	Next
End Sub

Sub SetServiceStartMode (p_serviceName, p_serviceStartMode)
' Check if service is in a certain startmode. Set it if it is not.
' Boot Start ("Boot") 		- Device driver started by the operating system loader. This value is valid only for driver services.
' System ("System") 		- Device driver started by the operating system initialization process. This value is valid only for driver services.
' Auto Start ("Automatic")	- Service to be started automatically by the service control manager during system startup.
' Demand Start ("Manual")	- Service to be started by the service control manager when a process calls the StartService method.
' Disabled ("Disabled")		- Service that can no longer be started.

	Dim objWMIService, cServices, oService
	Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
	Set cServices = objWMIService.ExecQuery("SELECT * FROM Win32_Service")
	
	For Each oService In cServices
		If LCase(oService.Name) = LCase(p_serviceName) Then
			If oService.StartMode <> p_serviceStartMode Then    
				oService.ChangeStartMode(p_serviceStartMode)
				LogEventHide "Service " & p_serviceName & " start mode is now " & p_serviceStartMode, 1
			Else
				LogEventHide "Service " & p_serviceName & " start mode was already " & p_serviceStartMode, 1
			End If
		End If  
	Next
End Sub

Sub SetRVMessaging (p_State)
' Enable/Disable Messaging
	If p_State = "true" Then
		SetServiceState "ActiveMQ", "Started"
		SetServiceState "RmsAliveService", "Started"
		SetServiceStartMode "ActiveMQ", "Automatic"
		SetServiceStartMode "RmsAliveService", "Automatic"
		LogEvent "Messaging enabled"
	ElseIf p_State = "false" Then
		SetServiceState "ActiveMQ", "Stopped"
		SetServiceState "RmsAliveService", "Stopped"
		SetServiceStartMode "ActiveMQ", "Disabled"
		SetServiceStartMode "RmsAliveService", "Disabled"
		LogEvent "Messaging disabled"
	Else
		LogEventHide "Messaging not defined!"
	End If

End Sub


Sub SetAllRVServicesState (p_State)
	Dim Service
	Dim Services : Services = Array()
	
	If strInstallMD = "true" _
	Then
		ReDim Preserve Services(UBound(Services) + 1) :	Services(UBound(Services)) = "ndGlobalLauncher"
		ReDim Preserve Services(UBound(Services) + 1) :	Services(UBound(Services)) = "ndinit"
		ReDim Preserve Services(UBound(Services) + 1) :	Services(UBound(Services)) = "mgsdl"
		ReDim Preserve Services(UBound(Services) + 1) :	Services(UBound(Services)) = "mgssecsvc"
	End If
	
	If strActiveMQ = "true" _
	Then
		ReDim Preserve Services(UBound(Services) + 1) :	Services(UBound(Services)) = "ActiveMQ"
		ReDim Preserve Services(UBound(Services) + 1) :	Services(UBound(Services)) = "RmsAliveService"
	End If

	If strType = "ds" _
	Then
		ReDim Preserve Services(UBound(Services) + 1) :	Services(UBound(Services)) = "ndGlobalLA"
	End If

	If strType = "as_rv" _
	Or strType = "as_rms" _
	Or strType = "custom" _
	Then
		ReDim Preserve Services(UBound(Services) + 1) :	Services(UBound(Services)) = "ndGlobalLA"
	End If
	
	' Start/Stop Services
	For Each Service In Services
		SetServiceState Service, p_State
	Next
	
End Sub
	
Function GetLocalUserName (strSID)
	Dim objWMIService
	Dim colAccounts
	Dim objAccount
	Dim objSid

	Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

	Set objSid = objWMIService.Get ("Win32_SID.SID='" & strSID & "'")	
	GetLocalUserName = objSid.ReferencedDomainName & "\" & objSid.AccountName

	If GetLocalUserName = "" Then
		LogEvent "Cannot determine local username for SID " & strSID
		LogEvent "Exiting..."
		ScriptQuit 1
	End If
	
	Set objWMIService = Nothing
	Set colAccounts = Nothing
	Set objAccount = Nothing

End Function

Function GetLocalUserCaption (strSID)
	Dim objWMIService
	Dim colAccounts
	Dim objAccount
	Dim objSid

	Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

	Set colAccounts = objWMIService.ExecQuery _
		("Select * From Win32_Account Where SID = '" & strSID & "' AND LocalAccount = True")

	For Each objAccount In colAccounts
		GetLocalUserCaption = objAccount.Caption
	Next
	
	If GetLocalUserCaption = "" Then
		LogEvent "Cannot determine local username for SID " & strSID
		LogEvent "Exiting..."
		ScriptQuit 1
	End If
	
	Set objWMIService = Nothing
	Set colAccounts = Nothing
	Set objAccount = Nothing

End Function

Function ReadRegStr (RootKey, Key, Value, RegType)
	
    Dim oCtx, oLocator, oReg, oInParams, oOutParams

    Set oCtx = CreateObject("WbemScripting.SWbemNamedValueSet")
    oCtx.Add "__ProviderArchitecture", RegType

    Set oLocator = CreateObject("Wbemscripting.SWbemLocator")
    Set oReg = oLocator.ConnectServer("", "root\default", "", "", , , , oCtx).Get("StdRegProv")

    Set oInParams = oReg.Methods_("GetStringValue").InParameters
    oInParams.hDefKey = RootKey
    oInParams.sSubKeyName = Key
    oInParams.sValueName = Value

    Set oOutParams = oReg.ExecMethod_("GetStringValue", oInParams, , oCtx)

    ReadRegStr = oOutParams.sValue

	set oCtx = Nothing
	set oLocator = Nothing
End Function

Sub WriteRegStr (RootKey, Key, ValueName, Value, RegType)
	
    Dim oCtx, oLocator, oReg, oInParams, oOutParams

    Set oCtx = CreateObject("WbemScripting.SWbemNamedValueSet")
    oCtx.Add "__ProviderArchitecture", RegType

    Set oLocator = CreateObject("Wbemscripting.SWbemLocator")
    Set oReg = oLocator.ConnectServer("", "root\default", "", "", , , , oCtx).Get("StdRegProv")

	'Create Key
	Set oInParams = oReg.Methods_("CreateKey").InParameters
    oInParams.hDefKey = RootKey
    oInParams.sSubKeyName = Key
 
    Set oOutParams = oReg.ExecMethod_("CreateKey", oInParams, , oCtx)
	
	'Create Value
    Set oInParams = oReg.Methods_("SetStringValue").InParameters
    oInParams.hDefKey = RootKey
    oInParams.sSubKeyName = Key
    oInParams.sValueName = ValueName
	oInParams.sValue = Value
 
    Set oOutParams = oReg.ExecMethod_("SetStringValue", oInParams, , oCtx)

	set oCtx = Nothing
	set oLocator = Nothing
End Sub


'Get Filename Without Extension
Function getFileNameWoExt(ByVal FileName)
  Dim Result, i
  Result = FileName
  i = InStrRev(FileName, ".")
  If ( i > 0 ) Then
    Result = Mid(FileName, 1, i - 1)
  End If
  getFileNameWoExt = Result
End Function

'Get Files from Folder by Extension
Function getFilesFromFolder(p_Folder, p_Extension)

	LogEventHide "Get all " & p_Extension & " from " & p_Folder, 1
	
	Dim objFSO, objFolder, objFile
	ReDim fileArray(-1)
	Set objFSO = CreateObject("Scripting.FileSystemObject")
	If objFSO.FolderExists(p_Folder) Then 
	
		Set objFolder = objFSO.GetFolder(p_Folder)

		For Each objFile In objFolder.Files
			If lcase(objFSO.GetExtensionName(objFile.Name)) = p_Extension Then
				ReDim Preserve fileArray(UBound(fileArray) + 1)
				'fileArray(UBound(fileArray)) = getFileNameWoExt(objFile.Name)
				fileArray(UBound(fileArray)) = objFile.Name
			End If
		Next
		
	Else
		LogEvent "Folder " + p_Folder + " does not exist "
	End If 

	getFilesFromFolder = fileArray

End Function


Function checkFileFolderByLength (p_folder, p_maxLength)
	
	Dim objFSO, objFolder, colFiles, objFile, subFolder
	On Error Resume Next
	
	checkFileFolderByLength = 0
	Set objFSO = CreateObject("Scripting.FileSystemObject")

	Set objFolder = objFSO.GetFolder(p_folder)

	Set colFiles = objFolder.Files

	If len(objFolder) >= p_maxLength Then 
		LogEventHide objFolder, 1
		checkFileFolderByLength = checkFileFolderByLength + 1
	End If

	For Each objFile in colFiles

		If len(objFile) >= p_maxLength Then 
			LogEventHide objFile, 1
			checkFileFolderByLength = checkFileFolderByLength + 1
		End If

	Next

	For Each subFolder in objFolder.subFolders
		checkFileFolderByLength = checkFileFolderByLength + checkFileFolderByLength(subFolder, p_maxLength)
	Next

End Function


'----- Deploy 
Sub DeployReports(p_Folder, strInstallPath, strSQLFullInstanceName, strMGSDatabase, strSQLServerUser, strSQLServerPass, strSSRSserverURL, strSSRSServerUser, strSSRSServerPass)

	'Procedure
	ReDim fileArray(-1)
	Dim element
	
	LogEvent "Deploy Reports"
	
	For Each element in getFilesFromFolder(p_Folder, "rss")
		' Exclude RSS with delete/remove
		If InStr( 1, element, "delete", 1 ) = 0 And InStr( 1, element, "remove", 1 ) = 0 Then
			LogEventHide "Source : " & p_Folder & "\" & element, 1
			
			strProcess = strSQLToolsPath32 & "rs.exe"
			strParam = "-l 600 -s """ & strSSRSserverURL & """" &_
			" -v installDir=""" & strInstallPath & """" &_
			" -v mgsDataServerName=""" & strSQLFullInstanceName & """" &_
			" -v mgsDataBaseName=""" & strMGSDatabase & """" &_
			" -v mgsAdministratorGroup=""MGS Administrators""" &_
			" -v mgsReportUsers=""MGS Report Users""" & _
			" -i """ & p_Folder & "\" & element & """"
			strFolder = p_Folder
			
			If strSQLServerAuth = "SQLServer" AND strSQLServerUser <> "" AND strSQLServerPass <> "" Then 
				strParam = strParam &_
				" -v domainName=""" & strSQLServerName & """" &_
				" -v mgsDataUserName=""" & strSVCAccountName & """" &_ 
				" -v mgsDataPassword=""" & strSVCAccountPwd & """" &_
				" -v mgsDataAuthType=""" & strSQLServerAuth & """" &_
				" -v mgsCredRetrieval=""Store"""
			Else 
				strParam = strParam &_ 
				" -v domainName=""" & strComputer & """" &_
				" -v mgsDataUserName=""""" &_
				" -v mgsDataPassword=""""" &_
				" -v mgsDataAuthType=""WindowsNT""" &_
				" -v mgsCredRetrieval=""Integrated"""
			End If
		
			If strSSRSServerUser <> "" AND strSSRSServerPass <> "" Then	
				strParam = strParam &_
				" -U " & strSSRSServerUser &_
				" -P " & strSSRSServerPass
			End If
			
			' Set fixed DNA database
			If strInstallDNA = "true" Then
				strParam = strParam &_ 
				"-v mgsDNADataServerName=""" & strSQLServerName & """" &_
				"-v mgsDNADataBaseName=""" & strDNADatabase & """"
			Else
				strParam = strParam &_ 
				" -v mgsDNADataServerName=""" & strSQLServerName & """" &_
				" -v mgsDNADataBaseName=""" & strMGSDatabase & """"
			End If

			ExecuteProcessPath strProcess, strParam, strFolder, 0, 0

			If Err.Number = 0 Then
				ReDim Preserve fileArray(UBound(fileArray) + 1)
				fileArray(UBound(fileArray)) = (UCase(Left(element, 1)) &  Mid(element, 2))
			End If
		End If	
	Next
	
End Sub

' Mask parts of a string
Private Function maskString(p_String, p_left, p_right)
	maskString=((Left(p_String, p_left)) &  String(LEN(p_String)-(p_left+p_right),"*") & (Right(p_String, p_right)))
End Function

'Checks if the script is running elevated (UAC)
Private Function isElevated()
	Dim shell, whoami, whoamiOutput, strWhoamiOutput
	Set shell = CreateObject("WScript.Shell")
	Set whoami = shell.Exec("whoami /groups")
	Set whoamiOutput = whoami.StdOut
	strWhoamiOutput = whoamiOutput.ReadAll

	If InStr(1, strWhoamiOutput, "S-1-16-12288", vbTextCompare) Then 
	isElevated = True
	Else
	  isElevated = False
	End If
End Function

'Re-runs the process prompting for priv elevation on re-run
Sub getUacPrompt(p_Arguments)
	Dim interpreter, shellApp
	'Check if we need to run in C or W script
	interpreter = "wscript.exe"
	If Instr(1, WScript.FullName, "CScript", vbTextCompare) = 0 Then
	interpreter = "wscript.exe"
	else
	interpreter = "cscript.exe"
	end if

	'Start a new instance with an elevation prompt first
	Set shellApp = CreateObject("Shell.Application")
	shellApp.ShellExecute interpreter, Chr(34) & WScript.ScriptFullName & Chr(34) & " " & p_Arguments &" uac", "", "runas", 1

	'End the non-elevated instance
	ScriptQuit 0
End Sub

'Get arguments
Private Function getArguments()
	Dim objArgs, strArg
	Set objArgs = Wscript.Arguments
	For Each strArg in objArgs
		getArguments = getArguments & " " & strArg
	Next
End Function

Sub Pause()
	Dim p
    WScript.Echo ("Press Enter to continue")
    p = WScript.StdIn.ReadLine()
End Sub

'Initiate Reboot, force
Private Sub initReboot(p_RebootMessage, p_RunOnce, p_nextStep)
	Dim intShutdown
	
	If isBlank(p_RebootMessage) Then p_RebootMessage = "Performing reboot"
	LogEvent p_RebootMessage
	
	If strDisplayMode <> "quiet" Then intShutdown = (MsgBox(p_RebootMessage,vbYesNo+vbExclamation+vbApplicationModal,"Reboot"))		
	
	If intShutdown = vbYes Or strDisplayMode = "quiet" Then
		
		' Set RunOnce
		If p_RunOnce = 1 Then 
			

			'Set explorer start
			If getOSVersion(strOSVersion) = "6.0" _
			Or getOSVersion(strOSVersion) = "6.1" _ 
			Or getOSVersion(strOSVersion) = "6.2" _
			Or getOSVersion(strOSVersion) = "6.3" _ 
			Then
				WriteRegStr HKCU, "Software\Microsoft\Windows\CurrentVersion\RunOnce", "2_" & strType, """" & strOSPath & "\System32\cscript.exe"" """ & WScript.ScriptFullName & """ ", 64
			Else
				WriteRegStr HKLM, "Software\Microsoft\Windows\CurrentVersion\RunOnce", "2_" & strType, """" & strOSPath & "\System32\cscript.exe"" """ & WScript.ScriptFullName & """ ", 64
			End If
			LogEvent "Continuing after reboot"
		End If
		
		If p_nextStep <> "" Then
			NextStep (p_nextStep)
		End If
		
		' Pause for dramatic effect
		wscript.sleep 1000 
		doReboot()
	End If
		
End Sub

Private Sub doReboot ()
	Dim OpSysSet, OpSys, retVal
	
	Set OpSysSet = GetObject("winmgmts:{authenticationlevel=Pkt," _
		 & "(Shutdown)}").ExecQuery("select * from Win32_OperatingSystem where "_
		 & "Primary=true")
		 
	For each OpSys in OpSysSet
		retVal = OpSys.Win32Shutdown(6)
	Next
	
	Wscript.Quit 0
End Sub


Private Sub ScriptQuit (p_rc)
	
	If p_rc <> 0 Then 
		Pause()
		If	strDisplayMode = "verbose" Then
			Dim objFSO
			Set objFSO = CreateObject("Scripting.FileSystemObject")
			strProcess = strOSPath & "\system32\notepad.exe"
			strFolder = strLogFolder
		
			' Open setup log
			If objFSO.FileExists(strLogFile) Then
				strParam = strLogFile
				ExecuteProcessPath strProcess, strParam, strFolder, 1, 0
			End If
			
			' Open last sub log
			If strSubLogFile <> "" Then
				If objFSO.FileExists(strSubLogFile) Then
					strParam = strSubLogFile
					ExecuteProcessPath strProcess, strParam, strFolder, 1, 0
				End If
			End If

			End If
	End If
	
	LogEventHide "Exiting Script with Returncode " & p_rc, 1
	Wscript.Quit p_rc
	
End Sub

Function requiredReboot()
	Dim objSysInfo
	requiredReboot = 0 + strRebootRequired
	
	Set objSysInfo = CreateObject("Microsoft.Update.SystemInfo")
	If CInt(objSysInfo.RebootRequired) <> 0 Then requiredReboot = requiredReboot + 1
	If Not isBlank(ReadRegStr (HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired", "(Default)", 64)) Then requiredReboot = requiredReboot + 1
	If Not isBlank(ReadRegStr (HKLM, "SYSTEM\CurrentControlSet\Control\Session Manager\PendingFileRenameOperations", "(Default)", 64)) Then requiredReboot = requiredReboot + 1
	
	LogEventHide "Reboot count : " & requiredReboot ,1
End Function

Function getOSName(p_OSCaption, p_OSVersion, p_OSArch)
	If InStr(p_OSCaption,"Server") > 1 AND getOSVersion(p_OSVersion) = "6.0" AND LCASE(p_OSArch) = "32-bit" Then getOSName = "Win2008_x86" End If
	If InStr(p_OSCaption,"Server") > 1 AND getOSVersion(p_OSVersion) = "6.0" AND LCASE(p_OSArch) = "64-bit" Then getOSName = "Win2008_x64" End If
	If InStr(p_OSCaption,"Server") > 1 AND getOSVersion(p_OSVersion) = "6.1" AND LCASE(p_OSArch) = "64-bit" Then getOSName = "Win2008R2" End If
	If InStr(p_OSCaption,"Server") > 1 AND getOSVersion(p_OSVersion) = "6.2" AND LCASE(p_OSArch) = "64-bit" Then getOSName = "Win2012" End If
	If InStr(p_OSCaption,"Server") > 1 AND getOSVersion(p_OSVersion) = "6.3" AND LCASE(p_OSArch) = "64-bit" Then getOSName = "Win2012R2" End If
	If InStr(p_OSCaption,"Server") > 1 AND getOSVersion(p_OSVersion) = "10.0" AND LCASE(p_OSArch) = "64-bit" Then getOSName = "Win2016" End If
End Function

Function getOSVersion(p_OSVersion)
	getOSVersion = LEFT(p_OSVersion,instr(p_OSVersion,".")+1) 
End Function

'returns True if Empty or NULL or Zero
Function isBlank(p_Value)
	If IsEmpty(p_Value) or IsNull(p_Value) Then
	 isBlank = True
	ElseIf VarType(p_Value) = vbString Then
	 If p_Value = "" Then
	  isBlank = True
	 End If
	ElseIf IsObject(p_Value) Then
	 If p_Value Is Nothing Then
	  isBlank = True
	 End If
	ElseIf IsNumeric(p_Value) Then
	 If p_Value = 0 Then
	  'wscript.echo " Zero p_Value found"
	  isBlank = True
	 End If
	Else
	 isBlank = False
	End If
End Function

Function inArray(p_value, p_array())
	Dim i
	
	inArray = False
	
	For i=0 to UBound(p_array)
		If lcase(p_array(i)) = lcase(p_value) Then 
			inArray = True
			Exit For
		End If
	Next
	
End Function

Function isValueInScope(p_value, p_scope(), p_default)
	Dim i
	
	For i=0 to UBound(p_scope)
		If lcase(p_scope(i)) = lcase(p_value) Then 
			isValueInScope = lcase(p_value)
			Exit For
		End If
	Next

	If isBlank(isValueInScope) Then isValueInScope = lcase(p_default)

End Function

Sub refreshEnvPath()
	Dim oShell, oEnvSys, oEnvPro
	
	'Get current and new Path Varialbe
	Set oShell = WScript.CreateObject("WScript.Shell")
	Set oEnvPro = oShell.Environment("PROCESS")
	Set oEnvSys = oShell.Environment("System")
	
	'Refresh current Path
	oEnvPro("PATH") = oEnvSys("PATH")
	
	'LogEventHide "Current Path: " & oEnvPro("PATH"), 1
	'LogEventHide "New Path: " & oEnvSys("PATH"), 1
	
	SET oEnvSys = NOTHING
	SET oEnvPro = NOTHING
	SET oShell = NOTHING
	
End Sub

Sub LicenseCounting(p_SQLFullInstanceName, p_Database, p_SQLServerUser, p_SQLServerPass, p_State)
	p_State = ucase(p_State)

	'Enable/Disable Task
	strProcess = strOSPath & "\system32\schtasks.exe"
	strParam = "/Change /" & p_State &" /TN ""ManageSoft\License Counting recalculate"""

	ExecuteProcess strProcess, strParam
	
	'Enable/Disable Trigger
	ExecSQLQuery p_SQLFullInstanceName, p_Database, p_SQLServerUser, p_SQLServerPass, p_State & " TRIGGER HardwareClassWmiDataTrigger ON HardwareClass;", "HardwareClassWmiDataTrigger"
	ExecSQLQuery p_SQLFullInstanceName, p_Database, p_SQLServerUser, p_SQLServerPass, p_State & " TRIGGER HardwareObjectWmiDataTrigger ON HardwareObject;", "HardwareObjectWmiDataTrigger"
	ExecSQLQuery p_SQLFullInstanceName, p_Database, p_SQLServerUser, p_SQLServerPass, p_State & " TRIGGER HardwarePropertyWmiDataTrigger ON HardwareProperty;", "HardwarePropertyWmiDataTrigger"
	ExecSQLQuery p_SQLFullInstanceName, p_Database, p_SQLServerUser, p_SQLServerPass, p_State & " TRIGGER HardwareValueWmiDataTrigger ON HardwareValue;", "HardwareValueWmiDataTrigger"
	
End Sub

Function GetIISPortBinding (p_Protocol, p_port)
	Dim oIIS, oSite, binding
	Dim bindings : bindings = Array()
	
	Set oIIS = GetObject("winmgmts:root\WebAdministration")       
	Set oSite = oIIS.Get("Site.Name='Default Web Site'") 
	bindings = oSite.Bindings
	GetIISPortBinding = "False"
	
	For Each binding In bindings   
		If binding.Protocol = p_Protocol _
		And InStr(binding.bindinginformation, p_port) <> 0 _ 
		Then
			GetIISPortBinding = "True"
			LogeventHide "Binding found : " & binding.Protocol & "/" & binding.BindingInformation, 1
		End if
	Next

End Function

Sub ResetIISPortBindings (p_Website, p_Protocol, p_port)
	DIM objWebService
	SET objWebService = GetObject( "IIS://" & strComputer & "/W3SVC" )
	EnumWebsite objWebService, p_Website, p_Protocol, p_port

End Sub

Sub EnumWebsite (objWebService, p_Website, p_Protocol, p_port)
    DIM oIIS, objWebServer, objWebServerRoot, strBindings, oBindingNew, oSite
    FOR EACH objWebServer IN objWebService

		If objWebserver.Class = "IIsWebServer" _
		Then
			If objWebServer.ServerComment = p_Website _
			Then
			SET objWebServerRoot = GetObject(objWebServer.adspath & "/root")
				LogEventHide "Webserver" & CRLF & _
						"Site ID = " & objWebserver.Name & CRLF & _
						"Comment = """ & objWebServer.ServerComment & """ " & CRLF & _
						"State   = " & State2Desc( objWebserver.ServerState ) & CRLF & _
						"Path   = " & objWebServerRoot.path & CRLF & _
						"LogDir  = " & objWebServer.LogFileDirectory & _
						"", 1
						
				' Enumerate the HTTP bindings (ServerBindings) and
				' SSL bindings (SecureBindings)
				strBindings = EnumBindings( objWebServer.ServerBindings ) & _
											EnumBindings( objWebServer.SecureBindings )
				IF NOT strBindings = "" THEN
						LogEventHide "Current bindings" ,1
						LogEventHide "IP Address" & TAB & _
												 "Port" & TAB & _
												 "Host" & _
												 "", 1
						LogEventHide strBindings, 1
				END IF

				' Reset Bindings for this domain
				objWebserver.Put "ServerBindings", ""
				objWebserver.SetInfo

				' add a new binding
				Set oIIS = GetObject("winmgmts:root\WebAdministration")
				Set oBindingNew = oIIS.Get("BindingElement").SpawnInstance_            
				oBindingNew.BindingInformation = "*:" & p_port & ":"          
				oBindingNew.Protocol = p_Protocol  
				Set oSite = oIIS.Get("Site.Name='" & p_Website & "'")
				oSite.Bindings= array(oBindingNew)
				oSite.put_
			END IF
		END IF
	NEXT
	
	FOR EACH objWebServer IN objWebService
		IF objWebserver.Class = "IIsWebServer" _
		THEN
			IF objWebserver.ServerComment = p_Website _
			THEN
				strBindings = EnumBindings( objWebServer.ServerBindings ) & _
								EnumBindings( objWebServer.SecureBindings )
				IF NOT strBindings = "" THEN
						LogEventHide "New bindings" ,1
						LogEventHide "IP Address" & TAB & _
												 "Port" & TAB & _
												 "Host" & _
												 "",1
						LogEventHide strBindings, 1
				END IF
			END IF
		END IF
	NEXT
END SUB

FUNCTION EnumBindings( objBindingList )
    DIM i, strIP, strPort, strHost
    DIM reBinding, reMatch, reMatches
    SET reBinding = NEW RegExp
    reBinding.Pattern = "([^:]*):([^:]*):(.*)"

    FOR i = LBOUND( objBindingList ) TO UBOUND( objBindingList )
        ' objBindingList( i ) is a string looking like IP:Port:Host
        SET reMatches = reBinding.Execute( objBindingList( i ) )
        FOR EACH reMatch IN reMatches
            strIP = reMatch.SubMatches( 0 )
            strPort = reMatch.SubMatches( 1 )
            strHost = reMatch.SubMatches( 2 )

            ' Do some pretty processing
            IF strIP = "" THEN strIP = "All Unassigned"
            IF strHost = "" THEN strHost = "*"
            IF LEN( strIP ) < 8 THEN strIP = strIP & TAB

            EnumBindings = EnumBindings & _
                           strIP & TAB & _
                           strPort & TAB & _
                           strHost & TAB & _
                           ""
        NEXT

        EnumBindings = EnumBindings & CRLF
    NEXT

END FUNCTION

FUNCTION State2Desc( nState )
    SELECT CASE nState
    CASE 1
        State2Desc = "Starting (MD_SERVER_STATE_STARTING)"
    CASE 2
        State2Desc = "Started (MD_SERVER_STATE_STARTED)"
    CASE 3
        State2Desc = "Stopping (MD_SERVER_STATE_STOPPING)"
    CASE 4
        State2Desc = "Stopped (MD_SERVER_STATE_STOPPED)"
    CASE 5
        State2Desc = "Pausing (MD_SERVER_STATE_PAUSING)"
    CASE 6
        State2Desc = "Paused (MD_SERVER_STATE_PAUSED)"
    CASE 7
        State2Desc = "Continuing (MD_SERVER_STATE_CONTINUING)"
    CASE ELSE
        State2Desc = "Unknown state"
    END SELECT

END FUNCTION


Function ExecSQLQueryWMI(p_query)
	REM On Error Resume Next
	Dim oWMISQL, iCountConn, iCountCluster, iCountInstance, oResult, oResultTmp, fld
	iCountInstance = 0
	oResult = createobject("adodb.recordset")
	' SQL 2005
	REM Set oWMISQL = GetObject("WINMGMTS:\\.\root\Microsoft\SqlServer\ComputerManagement")
	REM If Err.Number = 0 Then
		REM iCountInstance = iCountInstance + 1
		REM ExecSQLQueryWMI = ExecSQLQueryWMIopen(oWMISQL, p_query)
	REM End If
	
	' SQL 2008-2016 plus 2 newer Versions
	REM For iCountConn = 10 to 15
		REM Err.Clear
		REM Set oWMISQL = GetObject("WINMGMTS:\\.\root\Microsoft\SqlServer\ComputerManagement" & CStr(iCountConn))
		Set oWMISQL = GetObject("WINMGMTS:\\.\root\Microsoft\SqlServer\ComputerManagement13")
		If Err.Number = 0 Then 
			iCountInstance = iCountInstance + 1
			oResultTmp = ExecSQLQueryWMIopen(oWMISQL, p_query)
			If oResult.count = 0 Then 'Recordset empty
			wscript.echo "Create Result"
				for each fld in oResultTmp.fields
					oResult.fields.append fld
				next
				oResult.open
			End If
			do while not oResultTmp.eof
			wscript.echo "Insert into Result"
				for each fld in oResultTmp.Fields
					oResult(fld.name).value = fld.value
				next
				oResult.update
				oResultTmp.movenext
			loop
			oResultTmp = nothing
		End If
	REM Next

	If iCountInstance > 0 Then
		Logevent "Read from MS SQL Instances:" & iCountInstance
	Else
		Logevent "No SQL instances detected"
	End If
	ExecSQLQueryWMI = oResult
	
End Function

Function ExecSQLQueryWMIopen(p_WMISQL, p_query)
	On Error Goto 0
	Dim arrSQLProp, oSQLProp, sSQLSecurity, sSQLConnectStr, oSQLConnect, oSQLResult
	
	Set arrSQLProp = p_WMISQL.ExecQuery("select * from SqlServiceAdvancedProperty where SQLServiceType = 1 AND PropertyName ='VERSION'")

	For Each oSQLProp in arrSQLProp
		If isBlank(strSQLServerUser) Or isBlank(strSQLServerPass) Then
			sSQLSecurity = "Integrated Security=SSPI;"
		Else
			sSQLSecurity = "User Id=" & strSQLServerUser & ";Password=" & strSQLServerPass & ";"
		End If

		If oSQLProp.ServiceName = "MSSQLSERVER" Then
			sSQLConnectStr = "Provider=SQLOLEDB;Data Source=.;Database=master;" & sSQLSecurity
		Else
			sSQLConnectStr = "Provider=SQLOLEDB;Data Source=.\" & replace(oSQLProp.ServiceName,"MSSQL$","") & ";Database=master;" & sSQLSecurity
		End If
		
		Set oSQLConnect=CreateObject("ADODB.Connection")
		Call oSQLConnect.Open(sSQLConnectStr)
		Set oSQLResult = CreateObject("ADODB.Recordset")
		
		LogEventHide "Query database: " & p_query, 1
		'LogEventHide "Connection String: " & oSQLConnect, 1
		Call oSQLResult.Open(p_query, oSQLConnect)
		
		LogEventHide "Read Results", 1
		
		If oSQLResult.EOF Then 
			LogEventHide "There are no records to retrieve.", 1
		Else 
			Do Until oSQLResult.EOF
				if oSQLResult("Result") <> "" then wscript.echo oSQLResult("Result")
				'if oSQLResult.Fields.Item("Result").Value <> "" then wscript.echo oSQLResult.Fields.Item("Result").Value
				oSQLResult.MoveNext
			Loop
		End If
		REM Do Until oSQLResult.EOF
			REM sName		= oSQLResult.Fields.Item("name").Value
			REM sOwner		= oSQLResult.Fields.Item("owner").Value
			REM sCreationDate	= oSQLResult.Fields.Item("create_date").Value
			REM sCollation	= oSQLResult.Fields.Item("collation_name").Value
			REM sCompLevel	= oSQLResult.Fields.Item("compatibility_level").Value
			REM sState		= oSQLResult.Fields.Item("state_desc").Value
			REM sRecoveryModel	= oSQLResult.Fields.Item("recovery_model_desc").Value
			REM Call Log("M", "  - Retrieved database name: " & sName & ", created: " & sCreationDate)
			REM Call CreateHardwareInventoryRecordDatabase (replace(oSQLProp.ServiceName,"MSSQL$",""), sName, sCreationDate, sCollation, sState, sRecoveryModel)
			REM iCountDatabase = iCountDatabase + 1
			REM oSQLResult.MoveNext
		REM Loop
		
		Set ExecSQLQueryWMIopen = oSQLResult
		'Call oSQLResult.Close
		'Call oSQLConnect.Close
	Next

End Function