#!/bin/bash
# Copyright (C) 2000-2005 SWsoft. All rights reserved.
#
# This file may be distributed under the terms of the Q Public License
# as defined by Trolltech AS of Norway and appearing in the file
# LICENSE.QPL included in the packaging of this file.
#
# This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
# WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
#
# Script to start VPS was rebooted
#

CONF_DIR=/etc/sysconfig/vz-scripts
VE_INFO=/proc/vz/veinfo
REBOOT_MARK='reboot'
LOCKFILE='/var/lock/vereboot.lock'

[ -f /etc/sysconfig/vz ] || exit
. /etc/sysconfig/vz

function check_reboot()
{
	local veid=${1}
	local ve_root
	local allowreboot

	VEID=${veid}
	[ -f "${CONF_DIR}/${veid}.conf" ] || return
	eval ` (
		. /etc/sysconfig/vz;
		. ${CONF_DIR}/${veid}.conf;
		echo ve_root=${VE_ROOT}\;;
		echo allowreboot=${ALLOWREBOOT}\;;
	) `
	if [ ! -z "${allowreboot}" -a "x${allowreboot}" = "xno" ]; then
		return
	fi
	if [ -f "${ve_root}/${REBOOT_MARK}" ]; then
		[ -z "${LOGFILE}" ] || echo "`date --iso-8601=seconds`  vereboot : VPS ${veid} : reboot " >> ${LOGFILE}
		/usr/sbin/vzctl start ${veid} >/dev/null 2>&1
	fi
}

function lockfile()
{
	local tmpfile="${LOCKFILE}.$$"

	echo $$ > ${tmpfile} 2> /dev/null || exit

	ln ${tmpfile} ${LOCKFILE} >& /dev/null && {
		rm -f ${tmpfile}
		return
	}
	kill -0 `cat $LOCKFILE` >& /dev/null && {
		rm -f ${tmpfile}
		exit
	}
	ln ${tmpfile} ${LOCKFILE} >& /dev/null && {
		rm -f ${tmpfile}
		return
	}
	rm -f ${LOCKFILE} ${tmpfile}
	exit
}

lockfile

cd ${CONF_DIR} 2>/dev/null || exit 
VE_TOTAL=`ls -1 *.conf 2>/dev/null | sed s/.conf//`
VE_RUN=`cat ${VE_INFO} | awk '{
	if ($1 != 0) {
		if (i++)
			 printf("|");
		 printf("^%s$", $1);
	}
}'`

if [ -z "${VE_RUN}" ]; then
	VE_STOPPED="${VE_TOTAL}"
else
	VE_STOPPED=`echo -e "${VE_TOTAL}" | egrep -v "${VE_RUN}"`
fi

for i in ${VE_STOPPED}; do
	check_reboot ${i}
done

rm -f ${LOCKFILE}
exit 0
