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 salve agent.    
const PVA_MN_CORE=0' 1

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

' Call configuration script
ConfigureCore

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

'
' Functions
'
Sub ConfigureCore()
	LogProgress "Starting core preupgrade configuration"

	Dim v
	v = CheckPreviousVersion

	If v(0) < 4 Then
		LogError -1, "Unsupported version " & v(0)
		WScript.Quit(-1)
	End If

	If 4 < v(0) Or v(1) = 6 Then 
		Do46PreUpdate
	ElseIf v(1) = 5 Then
		If v(2) = 1356 Then
			Do45_1356_upgrade
		Else
			LogError -1, "Only 4.5.1356 -> 4.6 upgrades are supported. Please update your PVA 4.5 installation to 4.5.1356 version first."
			WScript.Quit(-1)
		End If
	Else
		LogError -1, "Unsupported version " & v(0) & "." & v(1)
		WScript.Quit(-1)
	End IF
	
	LogProgress "Core preupgrade configuration finished succesfully"
End Sub

Function CheckPreviousVersion
	LogProgress "Checking if PVA 4.5 is installed"
	Dim output
	output = GetInstalledVersion
	If Not IsNull(output) Then
		LogProgress "Found installed version " & output(0) & "." & output(1) & "." & output(2)
		If (4 = output(0) And output(1) >= 5 And output(2) >= 1230) Or (output(0) > 4) Then
			CheckPreviousVersion = output
			Exit Function
		End If
	End If
	LogError -1, "You can not upgrade from PVA with version less then 4.5-1230"
	WScript.Quit(-1)
End Function

Sub Do46PreUpdate
	StopService GetAgentServiceName(PVA_MN_CORE)
End Sub

Sub Do45_1356_upgrade
	LogProgress "Performing 4.5 -> 4.6 upgrade"
	StopService GetAgentServiceName(PVA_MN_CORE)
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
