#!/bin/bash
#  Copyright (C) 2000-2007 SWsoft. All rights reserved.
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
#
# Script to start VE was rebooted
#

VZCONF=/etc/vz/vz.conf
CONF_DIR=/etc/vz/conf
VESTAT=/proc/vz/vestat
REBOOT_MARK='reboot'
LOCKFILE='/var/lock/vereboot.lock'

[ -f ${VZCONF} ] || exit
. ${VZCONF}

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

	VEID=${veid}
	[ -f "${CONF_DIR}/${veid}.conf" ] || return
	eval ` (
		. ${VZCONF};
		. ${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 : VE ${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
}

# If VZ is not running -- do nothing
# Fix for OpenVZ bug #107
test -f ${VESTAT} || exit 0
lockfile

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

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
