#!/bin/bash

############################ Variables ############################

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

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

PVA_SQL_USER=vzagent

MYSQLD_CONFIG=/etc/my.cnf

######################### Implementation  #########################
# enable service
function service_enable()
{
	MSG=`whereis -b chkconfig | awk '{print$2}'`
	if test -f "$MSG"; then
		local action=$1
		shift
   
		for i in $@; do
			echo "# Setting service $i $action"
			$MSG $i $action || abort "Can't configure startup of $i"
		done
	else
		abort "# Failed to find chkconfig"
	fi
}

# adjust mysql config file
function mysql_configure()
{
    local config_path=${MYSQLD_CONFIG}
    echo "config_path=${MYSQLD_CONFIG}"
    [ -f ${config_path} ] || touch ${config_path}

    echo "# Configuring MySQL"

    if grep -q -e "^[ ]*innodb_data_file_path" ${config_path}; then
        :
    else
        echo -ne "\n[mysqld]\ninnodb_data_file_path=ibdata1:10M:autoextend\n" >> ${config_path}
    fi
    if grep -q -e "^[ ]*bind-address[ ]*=" ${config_path}; then
        :
    else
        echo -ne "\n[mysqld]\nbind-address=127.0.0.1\n" >> ${config_path}
    fi
}

# restart MySQL
function mysql_restart()
{
    echo "# Restarting MySQL"

    /etc/init.d/$MYSQL_SERVICE restart || abort "Failed to restart MySQL"
}


#----------------------------------------------------------------------------

# perform any operation with service
function service_control()
{
    local action=$1
    shift
    for i in $@; do
        echo "# Executing $i $action"
        /etc/rc.d/init.d/$i $action || [ "$action" = "stop" ] || abort "Can't $action $i"
    done
}

function replaceInFile()
{
	local fileName=$1
	local replaceFrom=$2
	local replaceTo=$3
	echo "# Updating $fileName"
	sed -i -e "s#${replaceFrom}#${replaceTo}#g" $fileName || abort "Can't update $fileName"
}

function generateEID()
{
	echo "# Generating hardware node EID"
	EID=`${VZLCORE_BIN_DIR}/guidgen`
	echo "# Hardware node EID is ${EID}"

	if [[ $PVA_MN_CORE == 0 ]]; then
		if [ -e "${PVA_40_45_UPGRADE_FOLDER}/vzagent/etc/vzagent.conf" ]; then
			echo "# Getting hardware node EID from PIM 4.0 configuration"
			EID=`${VZLCORE_BIN_DIR}/vzlxmlman -g data/system/configuration/id "${PVA_40_45_UPGRADE_FOLDER}/vzagent/etc/vzagent.conf"`
			echo "# Hardware node EID is ${EID}"
		fi
	fi
	[ -n "$EID" ] || abort "Failed to generate EID"
}

function generateSqlUserPassword()
{
	echo "# Generating SQL user password"
	pvaSqlUserPassword=`${VZLCORE_BIN_DIR}/guidgen`
	[ -n "$EID" ] || abort "Failed to generate SQL user password"
}

# Modify XML data
function setXMLTagValue()
{
	local tag=$1
	local value=$2
	local file=$3
	${VZLCORE_BIN_DIR}/vzlxmlman -s "$value" -i "$tag" $file
}

function configureAgentDataDir()
{
	echo "# Creating PVA Agent configuration files"

	echo "# Removing old data directories"
	rm -rf $VZLCORE_PSTORAGE_DIR
	rm -rf $VZLCORE_ETC_DIR
	rm -rf $VZLCORE_TMP_DIR
	rm -rf $VZLCORE_LOG_DIR

	echo "# Creating new data directories"
	checkBrokenLinks
	mkdir -p $VZLCORE_CHANGEABLE_DIR || abort Failed to create $VZLCORE_CHANGEABLE_DIR
	mkdir -p $VZLCORE_ETC_DIR || abort Failed to create $VZLCORE_ETC_DIR
	mkdir -p $VZLCORE_DUMPS_DIR || abort Failed to create $VZLCORE_DUMPS_DIR
	mkdir -m 700 -p $VZLCORE_TMP_DIR || abort Failed to create $VZLCORE_TMP_DIR
	mkdir -p $VZLCORE_LOG_DIR || abort Failed to create $VZLCORE_LOG_DIR
	cp -afr $VZLCORE_INSTALL_DIR/install/etc/* $VZLCORE_ETC_DIR || abort Failed to initialize $VZLCORE_ETC_DIR
	mkdir -m 700 $VZLCORE_PSTORAGE_DIR || abort "Can't create pstorage directory"

	# Save vzagent credentials
	# echo -ne "${PVA_SQL_USER}\n${pvaSqlUserPassword}" | ${VZLCORE_BIN_DIR}/base64 > ${VZLCORE_PSTORAGE_DIR}/${PVA_SQL_USER} || abort "Failed to save ${PVA_SQL_USER} credentials"
	echo -n "${EID}" >${VZLCORE_ETC_DIR}/eid || abort "Failed to save EID to ${VZLCORE_ETC_DIR}"

	echo "# Import plugins to vzagent.conf"
	for i in `ls ${VZLCORE_PLUGINS_DIR}/*/*.conf`; do
		${VZLCORE_BIN_DIR}/vzlconf_update ${VZLCORE_ETC_DIR}/vzagent.conf $i ${VZLCORE_ETC_DIR}/vzagent.conf || abort "Failed to import plugin $i to vzagent.conf"
	done

	echo "# Writing EID to agent config file"
	setXMLTagValue "data/system/configuration/id" ${EID} ${VZLCORE_ETC_DIR}/vzagent.conf || abort "Failed to save EID to ${VZLCORE_ETC_DIR}/vzagent.conf"

	echo "# Updating PVA agent listeners list"
	replaceInFile $VZLCORE_ETC_DIR/vzagent.conf $PVA_TCP_PORT_PLACEHOLDER $PVA_TCP_PORT
	replaceInFile $VZLCORE_ETC_DIR/vzagent.conf $PVA_SSL_PORT_PLACEHOLDER $PVA_SSL_PORT

	echo "# Updating pva.conf configuration file"
	[ -f $VZLCORE_BIN_DIR/pva.conf ] && rm -f $VZLCORE_BIN_DIR/pva.conf
	cp $VZLCORE_BIN_DIR/pva.conf.orig $VZLCORE_BIN_DIR/pva.conf
	replaceInFile $VZLCORE_BIN_DIR/pva.conf \\\[service\\\] 1
	replaceInFile $VZLCORE_BIN_DIR/pva.conf \\\[install_folder\\\] $VZLCORE_INSTALL_DIR
	replaceInFile $VZLCORE_BIN_DIR/pva.conf \\\[log_folder\\\] $VZLCORE_LOG_DIR
	replaceInFile $VZLCORE_BIN_DIR/pva.conf \\\[base_folder\\\] $VZLCORE_FHS_CHANGEABLE_DIR
	replaceInFile $VZLCORE_BIN_DIR/pva.conf \\\[etc_folder\\\] $VZLCORE_ETC_DIR
}

function checkBrokenLinks()
{
	PVADirs=(${VZLCORE_CHANGEABLE_DIR} ${VZLCORE_DUMPS_DIR} ${VZLCORE_ETC_DIR} ${VZLCORE_LOG_DIR} ${VZLCORE_FHS_CHANGEABLE_DIR})
    
	for i in ${PVADirs[*]}; do
		test -h $i && test ! -e $(ls -l $i | awk '{print$11}')
		if [ $? -eq 0 ]; then
			echo "# Broken link detected: $i"
			rm $i
		fi
	done
}

# Execute all sql scripts
function execAllSql()
{
	[ -d "${VZLCORE_SQL_DIR}" ] || return 1

	echo "# Executing SQL scripts"
	SQLscripts=`cat "${VZLCORE_SQL_DIR}/sql_scripts.list"`
	[ $? -eq 0 ] || abort "Failed to find ${VZLCORE_SQL_DIR}/sql_scripts.list"
    
	for i in ${SQLscripts[*]}; do
		sed -e "s/$DEFAULT_EID/$EID/g" ${VZLCORE_SQL_DIR}/$i > ${VZLCORE_SQL_DIR}/$i.tmp
		execSql ${VZLCORE_SQL_DIR}/$i.tmp
	done
}

# Configure PVA Agent
function configurePVAAgent()
{
	local EID=$1

	rm -rf ${SYSTEM_SERVICE_DIR}${VZAGENT}
	ln -s ${VZASERVICE} ${SYSTEM_SERVICE_DIR}${VZAGENT}
	service_enable "on" "${VZAGENT}"
	
	[ -f /usr/sbin/vzagroup ] && rm -rf /usr/sbin/vzagroup
	ln -sf "${VZLCORE_BIN_DIR}/vzagroup" /usr/sbin/vzagroup || abort "Can't create /usr/sbin/vzagroup link"

	# Fix pvasqlserveraddress
	# TODO resolve pvasqlserveraddress issue
	cat /etc/hosts | grep -q pvasqlserveraddress
	if [ $? -ne 0 ]; then
		echo "127.0.0.1 pvasqlserveraddress" >> /etc/hosts
	fi
}

function configureLoopback()
{
	echo "# Configuring network"
	ifconfig lo | grep 127.0.0.1
	if [ $? -ne 0 ]; then
		ifconfig lo 127.0.0.1 || abort "Failed to configure loopback interface"
		ifconfig lo up || abort "Failed to activate loopback interface"
	fi
}

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

	# Stop services
	stop_vzagent_services

	generateEID
	generateSqlUserPassword

	# Run config scripts for PVA 
	configureAgentDataDir

	if [[ $PVA_MN_CORE == 1 ]]; then
		# Enable services
		service_enable "on" "$MYSQL_SERVICE"
		# Configure MySQL
		mysql_configure
		mysql_restart
		# Create databases
		execAllSql
	fi

	is_psbm
	if [ $? -eq 0 ]; then
		echo "# Enabling sendmail service"
		service_enable "on" "sendmail"
		service sendmail start

		echo "# Enabling PVA Agent ports"
		iptables -L PVA-INPUT > /dev/null 2>&1 
		if [[ $? -ne 0 ]]; then
			iptables -N PVA-INPUT || abort Failed to create iptables chain for PVA Agent
			iptables -A PVA-INPUT -p tcp --dport 4533 -j ACCEPT || abort Failed to enable 4533 port
			iptables -A PVA-INPUT -p tcp --dport 4534 -j ACCEPT || abort Failed to enable 4534 port
			iptables -A PVA-INPUT -p tcp --dport 4433 -j ACCEPT || abort Failed to enable 4433 port
			iptables -A PVA-INPUT -p tcp --dport 4434 -j ACCEPT || abort Failed to enable 4434 port
			iptables -A PVA-INPUT -p tcp --dport 4435 -j ACCEPT || abort Failed to enable 4435 port
			iptables -A PVA-INPUT -p tcp --dport 5800:5899 -j ACCEPT || abort Failed to enable VNC ports
			iptables -A PVA-INPUT -p tcp --dport 4643 -j ACCEPT || abort Failed to enable 4643 port
			iptables -A PVA-INPUT -p tcp --dport 8443 -j ACCEPT || abort Failed to enable 8443 port
			iptables -I INPUT 1 -p tcp -j PVA-INPUT || abort Failed to insert PVA-INPUT iptables rule
			service iptables save || abort Failed to save iptables rules
		fi
	fi

	# Configure loopback interface (required by RHEL3)
	configureLoopback

	# Configure Agent
	configurePVAAgent

	# Start services
	start_vzagent_services

	if [[ $PVA_MN_CORE == 0 ]]; then
		${VZLCORE_BIN_DIR}/vzlInstallHelper postUpgrade "${PVA_40_45_UPGRADE_FOLDER}/vzagent"
		rm -rf ${PVA_40_45_UPGRADE_FOLDER}.backup
		mv ${PVA_40_45_UPGRADE_FOLDER} ${PVA_40_45_UPGRADE_FOLDER}.backup
	fi

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

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

main $*

exit 0
