Option Explicit
On Error Resume Next

Include "pva-agent-helper.vbs"

' This constant is replaced by the build system. In the result script this bool value will reflect 
' the configfuration of the PVA core. If PVA_MN_CORE is 1, then we work for PVA management node core,
' otherwise the core we deal with is for slave agent.    
const PVA_MN_CORE=0' 1

Const VZToolsInstalledVersionsKey = "HKLM\SOFTWARE\SWSoft\VZTools\INSTALLED_VERSIONS"
Const VZToolsInstalledVersionsKey64 = "HKLM\SOFTWARE\Wow6432Node\SWSoft\VZTools\INSTALLED_VERSIONS"
Const VZToolsUpdates = "HKLM\SOFTWARE\SWSoft\VZTools\Updates\"
Const VZToolsUpdates64 = "HKLM\SOFTWARE\Wow6432Node\SWSoft\VZTools\Updates\"

LogProgress "Executing " & Wscript.ScriptName & " PVA_MN_CORE=" & PVA_MN_CORE

ConfigureCore

If Err.number = 0 Then
	LogProgress Wscript.ScriptName & " finished succesfully"
	WScript.Quit 0
Else
	FailedQuitErr "Failed to execute core preinstall configuration"
End If

Sub ConfigureCore
	LogProgress "Starting agent preinstall configuration"

	If StopService(GetAgentServiceName(PVA_MN_CORE)) = PVA_SERVICE_NOT_FOUND_ERROR Then Err.Clear

	If PVA_MN_CORE = 0 Then
		UninstallPreviousVersion
	End If

	LogProgress "Core preinstall configuration finished"
End Sub

Function GetVZLConfigFolder40
	Dim Value
	If ReadRegistryKey("HKLM\Software\SWsoft\VZAgent\CONFIGDIR", value) <> 0 Then
		If ReadRegistryKey("HKLM\Software\Wow6432Node\SWsoft\VZAgent\CONFIGDIR", value) <> 0 Then
			value = ""
		End if
	End If
	GetVZLConfigFolder40 = TrimSlashes(value)
End Function

Sub UninstallPreviousVersion
	LogProgress "Looking for PIM 4.0 installation"
	Dim installer, objArgs
	Set objArgs = WScript.Arguments

	Set installer = CreateObject("WindowsInstaller.Installer")
	Dim relatedProduct

	For Each relatedProduct In installer.RelatedProducts("{6F8A99AF-96C7-482D-941E-96796F249721}")
		LogProgress "Trying to uninstall PIM 4.0"
		Dim pim40 : pim40 = GetVZLConfigFolder40()
		If pim40 <> "" Then
			Dim tempDir : tempDir = GetTempFolder() & "\" & PVA_40_45_UPGRADE_FOLDER
			DeleteFolderSafe tempDir
			CreateFolder tempDir

			CopyFolder pim40, tempDir
		End If

		RemoveSVePostStartCmd
		RemoveVZToolsUpdates
		StopPIM40Services
		If RemoveProduct(relatedProduct, installer.ProductInfo(relatedProduct, "InstalledProductName")) <> 0 Then
			FailedQuitErr "Can't uninstall " & relatedProduct
		End If
	Next

	If Err.number <> 0 Then
		LogProgress "Failed to uninstall PIM"
	End If
End Sub

Function RemoveProduct(key, productName)
	On Error Resume Next
	LogProgress "Trying to uninstall product " & productName & ", " & key
	Dim installer, objArgs
	Set objArgs = WScript.Arguments
	Set installer = CreateObject("WindowsInstaller.Installer")
	If objArgs.Named.Exists("log") Then
		installer.EnableLog "v", objArgs.Named.Item("log") & "\" & productName & "-" & key & "-uninstall.log"
	End If

	installer.UILevel = 64
	installer.ConfigureProduct key, 0, 2
	RemoveProduct = Err.Number
End Function

Sub RemoveVZToolsUpdates
	LogProgress "Starting PIM 4.0 hotfix uninstallation"
	Dim versionsList
	If ReadRegistryKey(VZToolsInstalledVersionsKey, versionsList) = 1 Then
		If ReadRegistryKey(VZToolsInstalledVersionsKey64, versionsList) = 1 Then		 
			FailedQuitErr "Can't read " & VZToolsInstalledVersionsKey
		End If
	End if
		
	Dim versionsListArray
	versionsListArray = Split(versionsList)
	
	LogProgress "RemoveVZToolsUpdates: UBound(versionsListArray) = " & CStr(UBound(versionsListArray))

	If UBound(versionsListArray) <> 0 Then
		Dim i, j, updateVersion, productCode
		For i=1 To UBound(versionsListArray)
			
			j = UBound(versionsListArray) + 1 - i
				
			updateVersion = versionsListArray(j)
			' Get update product code
			If ReadRegistryKey(VZToolsUpdates & updateVersion & "\PRODUCTCODE", productCode) <> 0 Then
				If ReadRegistryKey(VZToolsUpdates64 & updateVersion & "\PRODUCTCODE", productCode) <> 0 Then
					FailedQuitErr "Can't read " & keyUpdates & updateVersion & "\PRODUCTCODE"
				End If
			End If
		
			StopPIM40Services
			If RemoveProduct(productCode, "PIM4.0HF") <> 0 Then
				FailedQuitErr "Can't uninstall " & productCode
			End If
		Next
		
	End If
	LogProgress "PIM 4.0 hotfix uninstallation has finished"
End Sub

Sub RemoveSVePostStartCmd
	If GetVzClusterState = PVA_CS_STANDBY Then
		Exit Sub
	End If
	Dim r, c
	c = getVirtuozzoRootFolder(r)
	If Not c = 0 Then
		FailedQuitEx c, "Failed to read the Virtuozzo root path from registry"
	End If
	DeleteFile r & "\private\1\Scripts\vz-poststart.cmd"
End Sub

Function StopPIM40ClusterService(name)
	Dim c, e, o, p
	p = GetVzBinPath("vzcluster") & " service " & name & " --offline"
	c = ExecProgram(p, "", o, e)
	If Not c = 0 Then
		LogError c, "Failed to stop service " & name & ": " & e
	End If
	StopPIM40ClusterService = c
End Function

Sub StopPIM40Services
	If GetVzClusterState = PVA_CS_ACTIVE Then
		StopPIM40ClusterService("VZAOpCompat")
		StopPIM40ClusterService("VZAOp")
	Else
		StopService "VZAOpCompat"
		StopService "VZAOp"
	End If
End Sub

' Include vzlVBLib.vbs
Sub Include(cNameScript)
	On Error Resume Next
	Dim oFS, oFile
	
	cNameScript = Mid(Wscript.ScriptFullName, 1, InStrRev(Wscript.ScriptFullName, "\")) & cNameScript
	
	Set oFS = CreateObject("Scripting.Filesystemobject")
	
	Set oFile = oFS.OpenTextFile(cNameScript)
	If Err.number <> 0 Then
		WScript.Echo "Failed to open include file '" & cNameScript & "' - " & Err.source & ", " & Err.Description
		WScript.Quit(-1)
	End If
	
	ExecuteGlobal oFile.ReadAll()
	If Err.number <> 0 Then
		WScript.Echo "Failed to ExecuteGlobal include file '" & cNameScript & "' - " & Err.source & ", " & Err.Description
		WScript.Quit(-1)
	End If

	oFile.Close
End Sub
