#!/bin/sh
#  Copyright (C) 2000-2010, Parallels, Inc. 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
#
#
# (Re)start those containers which were rebooted from the inside.

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"

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}\;"
	) `
	[ "$allowreboot" = 'no' ] && return
	if [ -f "$ve_root/$REBOOT_MARK" ]; then
		[ -z "$LOGFILE" ] ||
			echo "`date --iso-8601=seconds` vereboot : CT $veid : reboot " >> "$LOGFILE"
		/usr/sbin/vzctl start "$veid" >/dev/null 2>&1
	fi
}

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

	echo $$ >"$tmpfile" 2>/dev/null || exit
	if ln "$tmpfile" "$LOCKFILE" 2>/dev/null; then
		rm -f "$tmpfile"
		return
	fi
	if kill -0 `cat $LOCKFILE 2>/dev/null` 2>/dev/null; then
		# Process is still running
		rm -f "$tmpfile"
		exit
	else
		# Not running -- retry
		rm -f $LOCKFILE
	fi
	if ln "$tmpfile" "$LOCKFILE" 2>/dev/null; then
		rm -f "$tmpfile"
		return
	fi
	rm -f "$tmpfile" "$LOCKFILE"
	exit
}

# If VZ is not running -- do nothing
# Fix for OpenVZ bug #107
test -f "$VESTAT" || exit 0
lockfile
VE_STOPPED=$(/usr/sbin/vzlist -H -octid -S 2>/dev/null)
for i in $VE_STOPPED; do
	check_reboot "$i"
done

rm -f "$LOCKFILE"
exit 0
