#!/bin/bash

PVA_MN_CORE=0

dropSve()
{
	vzlist 1
	if [ $? -eq 0 ]; then
		echo "Removing Service Container"
		echo "Stopping SVE with CTID=1"
		MSG=`vzctl stop 1`
		[ $? -ne 0 ] && abort "Failed to stop SVE - ${MSG}"
		echo "Removing SVE with CTID=1"
		MSG=`vzctl destroy 1`
		[ $? -ne 0 ] && abort "Failed to remove SVE - ${MSG}"
	else
		echo "SVE is not found"
	fi
}

function checkPrerequisites()
{
	rpm -qi virtuozzo-release || is_psbm
	if [ $? -ne 0 ]; then
		abort "Virtuozzo is not installed"
	else
		service vz status
		if [ $? -ne 0 ]; then
			abort "Virtuozzo is not running"
		fi
		rm -rf ${PVA_40_45_UPGRADE_FOLDER}
		mkdir ${PVA_40_45_UPGRADE_FOLDER}
		cp -r /var/vzagent/ ${PVA_40_45_UPGRADE_FOLDER}
		rpm -q vzagent-opcontrol
		if [ $? -eq 0 ]; then
			dropSve
		fi

		echo "Cleaning up old VZagent files"
		rm -rf /var/vzagent
	fi
}

function getVEPrivate()
{
	VEID=$1
	. /etc/vz/conf/$VEID.conf	
	echo $VE_PRIVATE
}

cleanup_agent()
{
	local d private
	for d in `vzlist -o veid -H`; do
		private=`getVEPrivate ${d}`
		echo "Removing $private/.vza"
		rm -rf $private/.vza
	done
	echo "Removing ${VZLCORE_ETC_DIR}/configs/*"
	rm -rf ${VZLCORE_ETC_DIR}/configs/*
	echo "Removing ${VZLCORE_ETC_DIR}/samples/*"
	rm -rf ${VZLCORE_ETC_DIR}/samples/*
}

function main() 
{
	echo "------------------------------------------------------------------------------------------------"
	date "+%b %e %T PVA Agent for Virtuozzo pre install configuration : start"

	checkPrerequisites

#	cleanup_agent

	date "+%b %e %T PVA Agent for Virtuozzo pre install configuration : stop"
	echo "------------------------------------------------------------------------------------------------"
}

###################### Include common files #######################

# VZL defines
scriptDir=`dirname "$0"`
# VZL defines
. ${scriptDir}/pva-agent-helper.sh || abort "Failed to include ${scriptDir}/pva-agent-helper.sh" 

############################### Go  ##############################

main $*

exit 0
