Option Explicit
On Error Resume Next

Include "pva-agent-helper.vbs"
const PVA_MN_CORE=0
const VZSRV_SERVICE = "vzsrv"
Dim ANONYMIZE
ANONYMIZE = 0

LogProgress "Executing " & Wscript.ScriptName

ParseCommandLine

If SafeGetDataDir(0) = "" or SafeGetInstallDir(0) = "" Then FailedQuit "Can not find agent installation path in registry."
	
ConfigureVZ

If Err.number = 0 Then
	LogProgress Wscript.ScriptName & " finished succesfully"
	WScript.Quit 0
Else
	FailedQuitErr "Failed to configure PVA agent for Virtuozzo"
End If


'
' Functions
'
Sub ConfigureVZ
	LogProgress "Starting PVA Agent for Virtuozzo configuration"

	' Remove cached agent data
	If GetVzClusterState <> PVA_CS_STANDBY And ANONYMIZE Then RemoveAgentData
	RegisterAgentService Array(VZSRV_SERVICE)

	' Register agent resource on active cluster node
	If GetVzClusterState = PVA_CS_ACTIVE Then
		RunVzCluster("addagentresources")
	End If

	' Make copies to keep the backward compatibility
	Dim fso, b
	Set fso = CreateObject("Scripting.FileSystemObject")
	b = GetBinDir(PVA_MN_CORE)
	fso.CopyFile b & "\pvareport.vbs", b & "\vzagentCollectReport.vbs"
	fso.CopyFile b & "\pvaprintreport.vbs", b & "\vzagentInfoReport.vbs"

	LogProgress "PVA Agent for Virtuozzo configured succesfully"
End Sub

Sub RemoveAgentData
	Dim fso
	Dim folder
	Dim parentFolder
	Dim Value
	
	LogProgress "Removing cached VZAgent data"
	
	If ReadRegistryKey("HKLM\Software\SWsoft\Virtuozzo\VZPRIVATE", Value) <> 0 Then
			Value = vzlRootFolder & "\private"
	End If

	Set fso = CreateObject("Scripting.FileSystemObject")
	Set parentFolder = fso.GetFolder(Value)
	For Each folder in parentFolder.SubFolders
		DeleteFolder folder & "\.vza"
	Next
	
End Sub

Sub ParseCommandLine()
	If WScript.Arguments.Count() > 0 Then
		Dim i
		For i=0 To WScript.Arguments.Count()
			Select Case WScript.Arguments(i)
				Case "--anonymize"
					LogProgress "Anonymization requested - clean cached agent data"
					ANONYMIZE = 1
			End Select
		Next
	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
