#!/bin/bash
###################### Include common files #######################
PVA_MN_CORE=0 #0
scriptDir=`dirname "$0"`
. ${scriptDir}/pva-agent-helper.sh || abort "Failed to include ${scriptDir}/pva-agent-helper.sh" 

############################### Go  ##############################
# Execute SQL script
function execSqlScript()
{
	if [[ $PVA_MN_CORE == 1 ]]; then
		execSql $1
	else
		sqlite3 $VZLCORE_ETC_DIR/VZAgentDB.sqldb ".read $1"
	fi
}

function upgradeDb()
{
	[ -d "${VZLCORE_SQL_DIR}" ] || return 1

	echo "# Upgrading DB"
	SQLscripts=`cat "${VZLCORE_SQL_DIR}/dbupgradefiles.list"`
	[ $? -eq 0 ] || abort "Failed to find ${VZLCORE_SQL_DIR}/dbupgradefiles.list"
    
	for i in ${SQLscripts[*]}; do
		execSqlScript ${VZLCORE_SQL_DIR}/$i
	done

	if [[ $PVA_MN_CORE == 1 ]]; then
		EID=`cat ${VZLCORE_ETC_DIR}/eid`
		sed -e "s/$DEFAULT_EID/$EID/g" ${VZLCORE_SQL_DIR}/mysql_db_views.sql > ${VZLCORE_SQL_DIR}/mysql_db_views.sql.tmp
		execSql ${VZLCORE_SQL_DIR}/mysql_db_views.sql.tmp
	fi
}

function assureCorrectLayout()
{
	mkdir -p $VZLCORE_FHS_CHANGEABLE_DIR
	mkdir -p $VZLCORE_DUMPS_DIR
	mkdir -m 700 -p $VZLCORE_TMP_DIR
}

function upgradeRunLevels()
{
	service_enable "--del" "${VZAGENT}"
	service_enable "--add" "${VZAGENT}"
}

echo "------------------------------------------------------------------------------------------------"
date "+%b %e %T PVA postupgrade configuration : start"

stop_vzagent_services
upgradeDb
upgradeRunLevels
assureCorrectLayout
${VZLCORE_BIN_DIR}/vzlInstallHelper patchConfig
start_vzagent_services
     
date "+%b %e %T PVA postupgrade configuration : stop"
echo "------------------------------------------------------------------------------------------------"

