#!/bin/bash

# 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 slave agent.    
PVA_MN_CORE=1 #0

DEFAULT_EID="00000000-0000-0000-0000-000000000002"

function drop_vzagent_databases()
{
	echo "# Removing vzagent databases"

	local sqlFile="pim-agent-preuninstall.sql"
	local EID=`cat ${VZLCORE_ETC_DIR}/eid`

	dbNames=(VZLLogDB VZLResLog)
    
	for i in ${dbNames[*]}; do
		echo "drop database if exists \`${i}${DEFAULT_EID}\`" | sed "s/$DEFAULT_EID/$EID/g" > ${sqlFile}
		MSG=`${MYSQL_BIN} < ${sqlFile} 2>&1`
		[ $? -ne 0 ] && error "Failed to remove database ${i}- ${MSG}"
	done

	MSG=`echo "drop database if exists VZAgentDB" | ${MYSQL_BIN} 2>&1`
	[ $? -ne 0 ] && error "Failed to remove database VZAgentDB - ${MSG}"
	rm -f $sqlFile
}

# main
function main() 
{
	echo "------------------------------------------------------------------------------------------------"
	date "+%b %e %T PVA Agent preuninstall configuration : start"

	stop_vzagent_services
	if [[ $PVA_MN_CORE == 1 ]]; then
		drop_vzagent_databases
	fi

	service_enable "--del" "${VZAGENT}"
	rm -rf ${SYSTEM_SERVICE_DIR}${VZAGENT}

	date "+%b %e %T PVA Agent preuninstall configuration : stop"
	echo "------------------------------------------------------------------------------------------------"
}

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

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

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

main $*

exit 0
