Const CM_DBNAME = "Ensim_WVH_Configuration"
Const RM_DBNAME = "Ensim_ResourceManager"
Const STAT_DBNAME = "Ensim_Statistic"

Dim isWSH, args, shell, fso, cm_dbconn, rm_dbconn, stat_dbconn, rs, server, xmlfile, targetdir, data, isAppliance, enableService
Dim pluginversion, pluginmajorversion, pluginminorversion, pluginbuildnumber, plugintype, resourceTypes, rootElement

Call Main

Sub Main()
	Call GetEnv
	Call InitObjects
	Call CheckArgs
	Call GetData
	Call GetDBConnection
	Call RemoveFromDB

	if cm_dbconn <> Empty then
		cm_dbconn.CommitTrans
		cm_dbconn.Close
	end if

	if rm_dbconn <> Empty then
		rm_dbconn.CommitTrans
		rm_dbconn.Close
	end if

	if stat_dbconn <> Empty then
		stat_dbconn.CommitTrans
		stat_dbconn.Close
	end if
' -------------------------------------------------------
' Call the language pack installation at the end so that
' even if it fails rest of the installation is completed
' Language pack installation can be done manually
' -------------------------------------------------------

	'if plugintype = "CP" then
	'   if Data.item("type") = "Service" then
	'      Call InitLangPack
	'   end if
	'end if

End Sub


Sub GetEnv()
	On Error Resume Next
	isWSH = true
	Set args = WScript.Arguments
	if err.number then
		isWSH = false
		args = Split(Session.Property("CustomActionData"), ";")
	end if
	err.clear
End Sub

' -------------------------------------------------------
' Initialize some objects
' -------------------------------------------------------
Sub InitObjects()
	Set shell = CreateObject("WScript.Shell")
	Set fso = CreateObject("Scripting.FileSystemObject")
End Sub

' -------------------------------------------------------
' Check Arguments
' -------------------------------------------------------
Sub CheckArgs()
	if isWSH then
		argNum = args.Count
	else
		argNum = UBound(args)+1
	end if

	if argNum >= 1 then
		Call GetDBInfo()
	else
		if isWSH then
			Call Usage
		else
			Abort 1, "Invalid arguments"
		end if
	end if

	xmlfile = args(0)

	targetdirs = split(xmlfile, "\")
	dirargs = UBound(targetdirs)
	for i = 0 to dirargs-1
	   if i = 0 then
         targetdir = targetdirs(i)
	   else
         targetdir = targetdir&"\"&targetdirs(i)
	   end if
	next
End Sub

Sub GetDBInfo()
	server = shell.ExpandEnvironmentStrings("%COMPUTERNAME%")
End Sub

' --------------------------------------------------------------------------------
' Parsing the xml file
' --------------------------------------------------------------------------------
Sub GetData()
	Dim xmlDoc

    Set xmlDoc = CreateObject("Microsoft.XMLDOM")
    xmlfile = Replace(xmlfile, Chr(34), "")
    xmlDoc.Load(xmlfile)
    if xmlDoc.parseError.errorCode then
		Abort xmlDoc.parseError.errorCode, xmlDoc.parseError.reason
	end if
	Set data = ParseXML(xmlDoc.documentElement)
	Set rootElement = xmlDoc.documentElement
    Set xmlDoc = Nothing

End Sub

Function ParseXML(node)
	Dim thisDict, childDict, children
	Set thisDict = CreateObject("Scripting.Dictionary")

	Set children = node.childNodes
	For Each child in children
		'ParseXML works fine if there is one and only one instance
		'of an element with the same name under a parent element.
		'This requires the use of numTypes in our XMLs.
		'Since "Statistics" element can contain multiple instances
		'of "Statistic" element, avoid pushing it into the dictionary.
		if (child.nodeName <> "Statistics") then
			if child.firstChild.nodeTypeString = "text" then
				if thisDict.Exists(child.nodeName) then
					thisDict.Item(child.nodeName) = thisDict.Item(child.nodeName) & "<>" & child.text
				else
					thisDict.Add child.nodeName, child.text
				end if
			else
				Set childDict = ParseXML(child)
       				thisDict.Add child.nodeName, childDict
		       	end if
		end if
	Next
	Set ParseXML = thisDict
End Function

' -------------------------------------------------------------------------------
' Creating DB connection
' -------------------------------------------------------------------------------
Sub GetDBConnection()
	On Error Resume Next
	' Opening connection to Config Manager DB
	Set cm_dbconn = CreateObject("ADODB.Connection")
	DB_CONNECT_STRING = "Provider=SQLOLEDB.1;Data Source="&server&";Initial Catalog="&CM_DBNAME&";Trusted_Connection=Yes"
	call cm_dbconn.Open(DB_CONNECT_STRING)
	call cm_dbconn.BeginTrans
	CheckError 1, err.Description

	' Opening connection to Resource Manager DB
	Set rm_dbconn = CreateObject("ADODB.Connection")
	DB_CONNECT_STRING = "Provider=SQLOLEDB.1;Data Source="&server&";Initial Catalog="&RM_DBNAME&";Trusted_Connection=Yes"
	call rm_dbconn.Open(DB_CONNECT_STRING)
	call rm_dbconn.BeginTrans
	CheckError 1, err.Description

	' Opening connection to statistic DB
	Set stat_dbconn = CreateObject("ADODB.Connection")
	DB_CONNECT_STRING = "Provider=SQLOLEDB.1;Data Source="&server&";Initial Catalog="&STAT_DBNAME&";Trusted_Connection=Yes"
	call stat_dbconn.Open(DB_CONNECT_STRING)
	call stat_dbconn.BeginTrans
	CheckError 1, err.Description

	set rs = CreateObject("ADODB.Recordset")
End Sub


' ------------------------------------------------------------------------------
' Init DB
' ------------------------------------------------------------------------------
Sub RemoveFromDB()
	plugintype = "PE"
	Set resourceTypes = CreateObject("Scripting.Dictionary")
	rs.Open "Select * from ResourceType", rm_dbconn
	while NOT rs.EOF
		resourceTypes.Add rs("Name").Value, rs("Id").Value
		rs.MoveNext
	wend
	rs.Close

	if Data.item("type") = "Service" then
		Call RemoveService()
	elseif Data.item("type") = "ServiceComponent" then
		Call RemoveComponent()
	else
		Abort 1, "Type " & Data.item("type") & " is not supported"
	end if


	plugintype = "CP"
	if Data.item("type") = "Service" then
		ServiceName = Data.item("name")
		ServiceVersion = Data.item("version")
	elseif Data.item("type") = "ServiceComponent" then
		ServiceName = Data.item("ServiceName")
		ServiceVersion = Data.item("ServiceVersion")
	else
		Abort 1, "Type " & Data.item("type") & " is not supported"
	end if

	Call RemovePluginFromDB(Data.item("name"), Data.item("displayName"), ServiceName, ServiceVersion)
Echo "End with removing from db"
End Sub


' ------------------------------------------------------------------------------
' Let DB know there is a plugin to un-installed ( service(component)'s name and display name are used as plugin's )
' ------------------------------------------------------------------------------
Function RemovePluginFromDB(pluginname, plugindisplayname, servicename, serviceversion)
	on error resume next	
  
    Dim SystemServerID
	Dim ServiceID

	rs.Open "SELECT ServiceID FROM ServiceType WHERE Name = '" & servicename & "' AND Version= '" & serviceversion & "'", cm_dbconn
	if rs.EOF then
		Abort 1, "Service " & servicename & " [" & serviceversion & "] is not registered in database. "
	else
		ServiceID = rs("ServiceID")
	end if
	rs.Close

	'echo "Delete From SystemServerPlugin "&_
	'						"WHERE Name = '" & pluginname &_
	'						"' AND Type = '" & plugintype & "'"
							
	call cm_dbconn.Execute("Delete From SystemServerPlugin "&_
							"WHERE Name = '" & pluginname &_
							"' AND Type = '" & plugintype & "'")
	
End Function

' ------------------------------------------------------------------------------
' Remove service from DB
' ------------------------------------------------------------------------------
Sub RemoveService()
	on error resume next

	name = data.item("name")
	version = data.item("version")
	displayName = data.item("displayName")

	if data.Exists("displayVersion") then
		displayVersion = data.item("displayVersion")
	else
		displayVersion = version
	end if

	if data.Exists("l10nMsgId") then
		l10nMsgId = "'" & data("l10nMsgId") & "'"
	else
		l10nMsgId = "null"
	end if

	if (data.Exists("QuotaGroup")) then
		guid = data.item("QuotaGroup").item("GUID")
		if (data.item("QuotaGroup").Exists("QuotaType")) then
				quotaTypes = data.item("QuotaGroup").item("QuotaType")
		end if
	end if

	if data.Exists("DependingList") then
		DependingList = "'" & data("DependingList") & "'"
	else
		DependingList = "null"
	end if
	if data.Exists("ConflictingList") then
		ConflictingList = "'" & data("ConflictingList") & "'"
	else
		ConflictingList = "null"
	end if

	rs.Open "SELECT ServiceID FROM ServiceType WHERE Name = '" & name & "' AND Version = '" & version & "'", cm_dbconn
	serviceID = rs("ServiceID")
	rs.Close

	'Removing entries in the QuotaGroup, QuotaType and QuotaGroup_QuotaType tables
	if (data.Exists("QuotaGroup")) then
		if (data.item("QuotaGroup").Exists("QuotaType")) then
			dim quotaTypesArray
			dim quotaTypeColumns
			quotaTypesArray = split(quotaTypes, "<>")
			For Each quotaType in quotaTypesArray
				quotaTypeColumns = split(quotaType, ";") 'quotaTypeColumns is in GUID;Name;Description;Unit;UsageCollectionOnly;L10nMsgId,ResourceType format
				
				'Echo "Delete from Quota WHERE QuotaGroupID = '" & guid & "' AND QuotaTypeID = '" & quotaTypeColumns(0) & "'"
				call rm_dbconn.Execute("Delete from Quota WHERE QuotaGroupID = '" & guid & "' AND QuotaTypeID = '" & quotaTypeColumns(0) & "'")
				
				'ServiceQuota
				'Echo "Delete FROM ServiceQuota WHERE QuotaGroupID = '" & guid & "' AND QuotaTypeID = '" & quotaTypeColumns(0) & "'"
				call cm_dbconn.Execute("Delete FROM ServiceQuota WHERE QuotaGroupID = '" & guid & "' AND QuotaTypeID = '" & quotaTypeColumns(0) & "'")

				'QuotaGroup_QuotaType
				'Echo "Delete FROM QuotaGroup_QuotaType WHERE QuotaGroupId = '" & guid & "' AND QuotaTypeId = '" & quotaTypeColumns(0) & "'"
				call rm_dbconn.Execute("Delete FROM QuotaGroup_QuotaType WHERE QuotaGroupId = '" & guid & "' AND QuotaTypeId = '" & quotaTypeColumns(0) & "'")

				'QuotaType
				'Echo "Delete FROM QuotaType where Id = '" & quotaTypeColumns(0) & "'"
				call rm_dbconn.Execute("Delete FROM QuotaType where Id = '" & quotaTypeColumns(0) & "'")
			Next
		else
			'If Service has no QuotaTypes, still have to enter the QuotaGroup
			'Echo "Delete FROM ServiceQuota WHERE QuotaGroupID = '" & guid & "' AND QuotaTypeID = '" & quotaTypeColumns(0) & "'"
			call cm_dbconn.Execute("Delete FROM ServiceQuota WHERE QuotaGroupID = '" & guid & "' AND QuotaTypeID = '" & quotaTypeColumns(0) & "'")
		end if

		rs.Open "Select Id FROM Resource WHERE QuotaGroupId = '" & guid & "'", rm_dbconn
		resourceID = rs(0)
		rs.Close
	end if
	
	'Echo "Delete from Quota WHERE QuotaGroupID = '"& guid &"'"
	call rm_dbconn.Execute("Delete from Quota WHERE QuotaGroupID = '"& guid &"'")
	'Echo "Delete from Capacity where QuotaGroupID = '"& guid &"'"
	call rm_dbconn.Execute("Delete from Capacity where QuotaGroupID = '"& guid &"'")
	
	Set quotatypeids = CreateObject("Scripting.Dictionary")
	rs.Open "Select QuotaTypeID from QuotaGroup_QuotaType where QuotaGroupID='"& guid &"'", rm_dbconn
	while NOT rs.EOF
		quotatypeids.Add rs("QuotaTypeID").Value, rs("QuotaTypeID").Value
		rs.MoveNext
	wend
	rs.Close

	'Echo "Delete from QuotaGroup_QuotaType WHERE QuotaGroupID = '"& guid &"'"
	call rm_dbconn.Execute("Delete from QuotaGroup_QuotaType WHERE QuotaGroupID = '"& guid &"'")

	items = quotatypeids.Items 'Get the items
	for i = 0 to quotatypeids.Count-1
		'Echo "Delete from QuotaType where ID='"& items(i) &"'"
		call rm_dbconn.Execute("Delete from QuotaType where ID='"& items(i) &"'")
	next
	set quotatypeids = nothing

	'Echo "Delete from Resource where QuotaGroupId='"&guid&"'"
	call rm_dbconn.Execute("Delete from Resource where QuotaGroupId='"&guid&"'")
	'Echo "Delete from QuotaGroup WHERE ID = '"& guid &"'"
	call rm_dbconn.Execute("Delete from QuotaGroup WHERE ID = '"& guid &"'")

    'Update ResellerService table
	rs.Open "SELECT OUID FROM OU WHERE Type = 'ISP'", cm_dbconn
	if rs.EOF then
		Abort 1, "Cannot find ISP OUID in database."
	else
		ISPOUID = rs("OUID")
	end if
	rs.Close

	Set servicecomponentids = CreateObject("Scripting.Dictionary")			
	rs.Open "Select ServiceComponentID from ServiceComponentType WHERE ServiceID = "&ServiceID, cm_dbconn
	while NOT rs.EOF
		servicecomponentids.Add rs("ServiceComponentID").Value, rs("ServiceComponentID").Value
		rs.MoveNext
	wend
	rs.Close
	items = servicecomponentids.Items 'Get the items
	for i = 0 to servicecomponentids.Count-1
		'Echo "Delete from StatisticLog where StatisticInstanceID=(select StatisticInstanceID from StatisticInstance where ServiceComponentID="&items(i)&")"
		call stat_dbconn.Execute("Delete from StatisticLog where StatisticInstanceID=(select StatisticInstanceID from StatisticInstance where ServiceComponentID="&items(i)&")")
		'Echo "Delete from StatisticInstance where ServiceComponentID="&items(i)
		call stat_dbconn.Execute("Delete from StatisticInstance where ServiceComponentID="&items(i))
		
		'Echo "Delete from MonitorLog where MonitorInstanceID in (Select MonitorInstanceID from MonitorInstance where MonitorTypeID in (Select MonitorTypeID from MonitorType where ServiceComponentID="& items(i) &"))"
		call cm_dbconn.Execute("Delete from MonitorLog where MonitorInstanceID in (Select MonitorInstanceID from MonitorInstance where MonitorTypeID in (Select MonitorTypeID from MonitorType where ServiceComponentID="& items(i) &"))")
		
		'Echo "Delete from MonitorInstance where MonitorTypeID in (Select MonitorTypeID from MonitorType where ServiceComponentID="& items(i) &")"
		call cm_dbconn.Execute("Delete from MonitorInstance where MonitorTypeID in (Select MonitorTypeID from MonitorType where ServiceComponentID="& items(i) &")")
		
		'Echo "Delete from MonitorType where ServiceComponentID="& items(i)
		call cm_dbconn.Execute("Delete from MonitorType where ServiceComponentID="& items(i))
		
		'Echo "Delete from ServiceComponentTypeQuotaType where ServiceComponentID="&items(i)
		call cm_dbconn.Execute("Delete from ServiceComponentTypeQuotaType where ServiceComponentID="&items(i))
	next
	Set servicecomponentids = nothing

	'Echo "Delete from VirtualServiceComponent where VirtualServiceID in (select VirtualServiceID from VirtualService where ServiceID="& ServiceID &")"
	call cm_dbconn.Execute("Delete from VirtualServiceComponent where VirtualServiceID in (select VirtualServiceID from VirtualService where ServiceID="& ServiceID &")")
	'Echo "Delete from VirtualServiceComponentUser where VirtualServiceID in (select VirtualServiceID from VirtualService where ServiceID="& ServiceID &")"
	call cm_dbconn.Execute("Delete from VirtualServiceComponentUser where VirtualServiceID in (select VirtualServiceID from VirtualService where ServiceID="& ServiceID &")")
	'Echo "Delete from VirtualService where VirtualServiceID in (select VirtualServiceID from VirtualService where ServiceID="& ServiceID &")"
	call cm_dbconn.Execute("Delete from VirtualService where VirtualServiceID in (select VirtualServiceID from VirtualService where ServiceID="& ServiceID &")")
	'Echo "Delete from VirtualServiceUser where VirtualServiceID in (select VirtualServiceID from VirtualService where ServiceID="& ServiceID &")"
	call cm_dbconn.Execute("Delete from VirtualServiceUser where VirtualServiceID in (select VirtualServiceID from VirtualService where ServiceID="& ServiceID &")")
	'Echo "Delete from ResellerServiceComponent where ServiceID="& ServiceID
	call cm_dbconn.Execute("Delete from ResellerServiceComponent where ServiceID="& ServiceID)
	'Echo "Delete from ResellerService where ServiceID="& ServiceID
	call cm_dbconn.Execute("Delete from ResellerService where ServiceID="& ServiceID)
	'Echo "Delete from ServicePlanComponent where ServiceID="& ServiceID
	call cm_dbconn.Execute("Delete from ServicePlanComponent where ServiceID="& ServiceID)
	'Echo "Delete from ServicePlan where ServiceID="& ServiceID
	call cm_dbconn.Execute("Delete from ServicePlan where ServiceID="& ServiceID)
	'Echo "Delete from ServiceComponent where ServiceID="& ServiceID
	call cm_dbconn.Execute("Delete from ServiceComponent where ServiceID="& ServiceID)
	'Echo "Delete from ServiceComponentType where ServiceID="& ServiceID
	call cm_dbconn.Execute("Delete from ServiceComponentType where ServiceID="& ServiceID)

	Call CleanCronJobs(serviceID)
	Call RemovePluginFromDB(name, displayName, name, version)
	
	'Echo "Delete from SystemServerPlugin where ServiceID="& ServiceID
	call cm_dbconn.Execute("Delete from SystemServerPlugin where ServiceID="& ServiceID)

	'Echo "Delete from ServiceType where ServiceID="&serviceID
	call cm_dbconn.Execute("Delete from ServiceType where ServiceID="&serviceID)
End Sub

' ------------------------------------------------------------------------------
' Remove component from DB
' ------------------------------------------------------------------------------
Sub RemoveComponent()
	on error resume next

	name = data("name")
	version = data("version")
	displayName = data("displayName")
	
	if data.Exists("displayVersion") then
	   displayVersion = data.item("displayVersion")
	else
	   displayVersion = version
	end if

	if data.Exists("l10nMsgId") then
		l10nMsgId = "'" & data("l10nMsgId") & "'"
	else
		l10nMsgId = "null"
	end if
	IsStartable = data("IsStartable")
	IsConfigurable = data("IsConfigurable")
	IsRemotelyManagable = data("IsRemotelyManagable")
	ServiceName = data("ServiceName")
	ServiceVersion = data("ServiceVersion")
	if data.Exists("QuotaGroupID") then
		QuotaGroupID = "'" & data("QuotaGroupID") & "'"
	else
		QuotaGroupID = "null"
	end if
	if data.Exists("InstanceQuotaID") then
		InstanceQuotaID = data("InstanceQuotaID")
	else
		InstanceQuotaID = "null"
	end if
	if data.Exists("QuotaTypes") then
		quotaTypes = data.item("QuotaTypes").item("QuotaType")
	else
		quotaTypes = null
	end if

	if data.Exists("DependingList") then
		DependingList = "'" & data("DependingList") & "'"
	else
		DependingList = "null"
	end if
	if data.Exists("ConflictingList") then
		ConflictingList = "'" & data("ConflictingList") & "'"
	else
		ConflictingList = "null"
	end if

	if data.Exists("IsMandatory") then
		IsMandatory = data("IsMandatory")
	else
		IsMandatory = 0
	end if

	'have to have quotagroup if you have instance quota
	if ((QuotaGroupID = "null") and (InstanceQuotaID <> "null")) then
		Abort 1, "QuotaGroup is required if Instance Quota is specified."
	end if

	'Find Service
	rs.Open "SELECT ServiceID FROM ServiceType WHERE Name = '" & ServiceName & "' AND Version = '" & ServiceVersion & "'", cm_dbconn
	if rs.EOF then
		Abort 1, "Service "& ServiceName &" cannot be found in DB"
	else
		ServiceID = rs("ServiceID")
	end if
	rs.close

	rs.Open "SELECT ServiceID, ServiceComponentID FROM ServiceComponentType WHERE Name = '" & name & "' AND Version = '" & version & "'", cm_dbconn
	serviceID = rs("ServiceID")
	componentID = rs("ServiceComponentID")
	rs.Close

	rs.Open "Select Id from Resource WHERE QuotaGroupID = "&QuotaGroupID, rm_dbconn
	resourceID = rs("Id")
	rs.Close

	'Update ResellerServiceComponentConfig table
	rs.Open "SELECT OUID FROM OU WHERE Type = 'ISP'", cm_dbconn
	if rs.EOF then
		Abort 1, "Cannot find ISP OUID in database"
	else
		ISPOUID = rs("OUID")
	end if
	rs.Close

	rs.Open "SELECT ResellerServiceID FROM ResellerService WHERE ServiceID = "&ServiceID&" AND OUID = "&ISPOUID, cm_dbconn
	if rs.EOF then
		Abort 1, "Cannot find Reseller Service entry in database"
	else
		ResellerServiceID = rs("ResellerServiceID")
	end if
	rs.Close

	'Echo "Delete from ResellerServiceComponent WHERE ServiceID="&ServiceID&" and ServiceComponentID="&componentID&" and ResellerServiceID="&ResellerServiceID
	call cm_dbconn.Execute("Delete from ResellerServiceComponent WHERE ServiceID="&ServiceID&" and ServiceComponentID="&componentID&" and ResellerServiceID="&ResellerServiceID)

    'Update the QuotaType table to make sure it has the Instance Quota, if required
    if InstanceQuotaID <> "null" then
		Dim InstanceQuotaColumns
		InstanceQuotaColumns = split(InstanceQuotaID, ";") 'InstanceQuotaColumns is in GUID;Name;Description;Unit;UsageCollectionOnly,L10nMsgId,ResourceType format

		Set capacityids = CreateObject("Scripting.Dictionary")			
		rs.Open "Select Id from Capacity WHERE QuotaGroupID = "&QuotaGroupID, rm_dbconn
		while NOT rs.EOF
			capacityids.Add rs("Id").Value, rs("Id").Value
			rs.MoveNext
		wend
		rs.Close

		items = capacityids.Items 'Get the items 
		for i = 0 to capacityids.Count-1
			'Echo "Delete from Quota where CapacityId="&items(i)&" and QuotaTypeId='"&InstanceQuotaColumns(0)&"' and QuotaGroupId="&QuotaGroupID
			call rm_dbconn.Execute("Delete from Quota where CapacityId="&items(i)&" and QuotaTypeId='"&InstanceQuotaColumns(0)&"' and QuotaGroupId="&QuotaGroupID)
		next
		Set capacityids = nothing

		'Echo "Delete from Quota where ResourceId="&resourceID&" and QuotaTypeId='"&InstanceQuotaColumns(0)&"' and QuotaGroupId="&QuotaGroupID
		call rm_dbconn.Execute("Delete from Quota where ResourceId="&resourceID&" and QuotaTypeId='"&InstanceQuotaColumns(0)&"' and QuotaGroupId="&QuotaGroupID)  

		'Echo "Delete from ServiceComponentTypeQuotaType where ServiceComponentID="&componentID&" and QuotaTypeID='"&InstanceQuotaColumns(0)&"'"
		call cm_dbconn.Execute("Delete from ServiceComponentTypeQuotaType where ServiceComponentID="&componentID&" and QuotaTypeID='"&InstanceQuotaColumns(0)&"'")

		'Echo "Delete from QuotaGroup_QuotaType where QuotaTypeId='"&InstanceQuotaColumns(0)&"' and QuotaGroupId="&QuotaGroupID		
		call rm_dbconn.Execute("Delete from QuotaGroup_QuotaType where QuotaTypeId='"&InstanceQuotaColumns(0)&"' and QuotaGroupId="&QuotaGroupID)
		
		'Echo "Delete from QuotaType where Id='"&InstanceQuotaColumns(0)&"'"
		call rm_dbconn.Execute("Delete from QuotaType where Id='"&InstanceQuotaColumns(0)&"'")

	end if

	if (quotaTypes <> "null") then
		dim quotaTypesArray, quotaTypeColumns
		quotaTypesArray = split(quotaTypes, "<>")

		For Each quotaType in quotaTypesArray
			quotaTypeColumns = split(quotaType, ";") 'quotaTypeColumns is in GUID;Name;Description;Unit;UsageCollectionOnly,L10nMsgId,ResourceType format
			
			rs.Open "Select Id from Resource WHERE QuotaGroupID = "&QuotaGroupID, rm_dbconn
			resourceID = rs("Id")
			'Echo "Delete from Quota where ResourceId="&resourceID&" and QuotaTypeId='"&quotaTypeColumns(0)&"' and QuotaGroupId="&QuotaGroupID
			call rm_dbconn.Execute("Delete from Quota where ResourceId="&resourceID&" and QuotaTypeId='"&quotaTypeColumns(0)&"' and QuotaGroupId="&QuotaGroupID)
			rs.Close

			Set capacityids = CreateObject("Scripting.Dictionary")			
			rs.Open "Select Id from Capacity WHERE QuotaGroupID = "&QuotaGroupID, rm_dbconn
			while NOT rs.EOF
				capacityids.Add rs("Id").Value, rs("Id").Value
				rs.MoveNext
			wend
			rs.Close
			items = capacityids.Items 'Get the items 
			for i = 0 to capacityids.Count-1
				'Echo "Delete from Quota where CapacityId='"&items(i)&"' and QuotaTypeId='"&quotaTypeColumns(0)&"' and QuotaGroupId="&QuotaGroupID
				call rm_dbconn.Execute("Delete from Quota where CapacityId='"&items(i)&"' and QuotaTypeId='"&quotaTypeColumns(0)&"' and QuotaGroupId="&QuotaGroupID)
			next
			Set capacityids = nothing

			'Echo "Delete from ServiceComponentTypeQuotaType where ServiceComponentID="&componentID&" and QuotaTypeID='"&quotaTypeColumns(0)&"'"
			call cm_dbconn.Execute("Delete from ServiceComponentTypeQuotaType where ServiceComponentID="&componentID&" and QuotaTypeID='"&quotaTypeColumns(0)&"'")
			'Echo "Delete from QuotaGroup_QuotaType where QuotaGroupId="&QuotaGroupID&" and QuotaTypeId='"&quotaTypeColumns(0)&"'"
			call rm_dbconn.Execute("Delete from QuotaGroup_QuotaType where QuotaGroupId="&QuotaGroupID&" and QuotaTypeId='"&quotaTypeColumns(0)&"'")
			'Echo "Delete from QuotaType where Id='"&quotaTypeColumns(0)&"'"
			call rm_dbconn.Execute("Delete from QuotaType where Id='"&quotaTypeColumns(0)&"'")
		Next
	end if

	'Echo "Delete from ServicePlanComponent where ServiceID=" & serviceID & " and ServiceComponentID=" &ComponentID
	call cm_dbconn.Execute("Delete from ServicePlanComponent where ServiceID=" & serviceID & " and ServiceComponentID=" &ComponentID)
	
	'Echo "Delete from VirtualServiceComponentUser where VirtualServiceComponentID in (select virtualservicecomponentID from virtualservicecomponent where servicecomponentinstanceID in (select servicecomponentinstanceID from servicecomponent where ServiceComponentID="&ComponentID&"))"
	call cm_dbconn.Execute("Delete from VirtualServiceComponentUser where VirtualServiceComponentID in (select virtualservicecomponentID from virtualservicecomponent where servicecomponentinstanceID in (select servicecomponentinstanceID from servicecomponent where ServiceComponentID="&ComponentID&"))")

	'Echo "Delete from VirtualServiceComponent where ServiceComponentInstanceID in (Select ServiceComponentInstanceID from ServiceComponent where ServiceComponentID="&ComponentID&")"
	call cm_dbconn.Execute("Delete from VirtualServiceComponent where ServiceComponentInstanceID in (Select ServiceComponentInstanceID from ServiceComponent where ServiceComponentID="&ComponentID&")")

	'Echo "Delete From ServiceComponent where ServiceComponentID="&componentID&" and ResourceID="&resourceID&" and ServiceID="&ServiceID
	call cm_dbconn.Execute("Delete From ServiceComponent where ServiceComponentID="&componentID&" and ResourceID="&resourceID&" and ServiceID="&ServiceID)
	
	'Echo "Delete from ServiceComponentType where ServiceID=" & serviceID & " and ServiceComponentID=" &ComponentID
	call cm_dbconn.Execute("Delete from ServiceComponentType where ServiceID=" & serviceID & " and ServiceComponentID=" &ComponentID)

	' Insert monitor types for this service component
	Call RemoveMonitorTypes (componentID)
	Call RemoveStatisticInstances (componentID)
	Call RemovePluginFromDB(name, displayName, ServiceName, ServiceVersion)
End Sub


Sub RemoveMonitorTypes(componentID)
	on error resume next

	if data.Exists("Monitor") then
		Dim name, description, displayName, status
		numTypes = data.item("Monitor").item("numTypes")

		rs.Open "Select ServiceComponentInstanceID from ServiceComponent WHERE ServiceComponentID = '"&componentID&"'", cm_dbconn
		instanceID = rs("ServiceComponentInstanceID")
		rs.Close

		i = 0
		Do While i < CLng(numTypes)
		    monitorTypeName = "MonitorType" & (i + 1)
			
		    name = data.item("Monitor").item(monitorTypeName).item("name")
		    description = data.item("Monitor").item(monitorTypeName).item("description")
		    displayName = data.item("Monitor").item(monitorTypeName).item("displayName")
		    
   		    test_query = "SELECT MonitorTypeId FROM MonitorType WHERE Name = '" & name & "' AND ServiceComponentID = '" & componentID & "'"
		    rs.Open test_query, cm_dbconn
		    monitorTypeID = rs(0)
		    rs.Close
		    
			'Echo "Delete from MonitorLog where MonitorInstanceID in (Select MonitorInstanceID from MonitorInstance where MonitorTypeID='"&monitorTypeID&"' and ServiceComponentInstanceID='"&instanceID&"')"
			call cm_dbconn.Execute("Delete from MonitorLog where MonitorInstanceID in (Select MonitorInstanceID from MonitorInstance where MonitorTypeID='"&monitorTypeID&"' and ServiceComponentInstanceID='"&instanceID&"')")
			
			'Echo "Delete from MonitorInstance where MonitorTypeID='"&monitorTypeID&"' and ServiceComponentInstanceID='"&instanceID&"'"
			call cm_dbconn.Execute("Delete from MonitorInstance where MonitorTypeID='"&monitorTypeID&"' and ServiceComponentInstanceID='"&instanceID&"'")

			'Echo "Delete from MonitorType WHERE Name = '"& name & "' AND ServiceComponentID = '" & componentID & "'"
			call cm_dbconn.Execute("Delete from MonitorType WHERE Name = '"& name & "' AND ServiceComponentID = '" & componentID & "'")
		    i = i + 1
		Loop
	end if
End Sub

Sub RemoveStatisticInstances (componentID)
	on error resume next
	if (rootElement.selectnodes("Statistics").Length = 1) then
		Dim MonitorName		
		For Each child in rootElement.selectnodes("Statistics/Statistic")
			MonitorName = child.selectNodes ("MonitorName") (0).text  		    
		    'Echo "Delete FROM StatisticLog WHERE StatisticInstanceID in (Select StatisticInstanceID from StatisticInstance WHERE MonitorName = '" & MonitorName & "')"
		    call stat_dbconn.Execute("Delete FROM StatisticLog WHERE StatisticInstanceID in (Select StatisticInstanceID from StatisticInstance WHERE MonitorName = '" & MonitorName & "')")
		    'Echo "Delete FROM StatisticInstance WHERE MonitorName = '" & MonitorName & "'"
		    call stat_dbconn.Execute("Delete FROM StatisticInstance WHERE MonitorName = '" & MonitorName & "'")			
			'Echo "Delete from CronJob where Data='" & MonitorName & "'"
			call cm_dbconn.Execute("Delete from CronJob where Data='" & MonitorName & "'")
		Next
	end if
End Sub

Sub CleanCronJobs(ServiceID)
	' Zap all old cron jobs that this service has
	'Echo "DELETE FROM CronJob WHERE ServiceID = " & ServiceID
	call cm_dbconn.Execute("DELETE FROM CronJob WHERE ServiceID = " & ServiceID)
End Sub

Sub CheckError(ExitOnError, msg)
	On error resume next
	if err.number and ExitOnError = 1 then
		Abort err.number, msg
	else
		err.Clear
	end if
End Sub

Sub Echo(msg)
	if isWSH then
		WScript.Echo msg
	else
		MsgBox msg
	end if
end Sub

Sub Abort(exitCode, msg)
	on error resume next
	if rs <> Empty then
		rs.Close
	end if
	if cm_dbconn <> Empty then
		cm_dbconn.RollbackTrans
		cm_dbconn.Close
	end if
	if rm_dbconn <> Empty then
		rm_dbconn.RollbackTrans
		rm_dbconn.Close
	end if
	if rs <> Empty then
		rs.Close
	end if
	Echo msg
	WScript.Quit(exitCode) 'generate error in windows installer
End Sub

Sub Usage()
	scriptName = fso.GetFileName(WScript.ScriptFullName)
	
    WScript.Echo
    WScript.Echo "Usage:"
    WScript.Echo "  "&scriptName&" <XML file>"
    WScript.Echo
    WScript.Quit(1)
End Sub

