Option Explicit
On Error Resume Next

Include "pva-agent-helper.vbs"

const PVA_MN_CORE=0

LogProgress "Executing " & Wscript.ScriptName

If GetVzClusterState <> PVA_CS_STANDBY Then
	UpgradeDb
	StartService GetAgentServiceName(PVA_MN_CORE)
End If

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

' 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

Sub UpgradeDb
	LogProgress "Reading sql scripts list"
	Dim filesListText, f, d, filesList
	f = SafeGetDbScriptsFile(PVA_MN_CORE)
	d = DirName(f)
	filesListText = ReadFromFile(f)
	filesList = Split(filesListText, vbCrLf)

	Dim fileName
	For Each fileName In filesList
		If fileName <> "" Then
			ExecSQL d & "\" & fileName
		End If
	Next
End Sub

Sub ExecSQL(sqlscript)
	LogProgress "Executing SQL script " & sqlscript
	RunCommand GetBinDir(PVA_MN_CORE) & "\sqlite3exe.exe " & SafeGetDataDir(PVA_MN_CORE) & _
		"\etc\VZAgentDB.sqldb " & """.read '" & sqlscript & "'"""
End Sub

