#!/bin/sh
#  Copyright (C) 2000-2013, 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
#
# This script is run by vzeventd after CT is stopped. In case it was stopped
# not by vzctl, but from inside the CT itself (e.g. by running "halt" or
# "shutdown", we need to unmount it and clean its network resources.

VEINFO=/proc/vz/veinfo
test -n "$VEID" || exit 1
test -f @SCRIPTDIR@/vps-functions || exit 1
. @SCRIPTDIR@/vps-functions

clear_ve_net()
{
	local a ve_addresses all_addresses

	all_addresses=$(cat "$VEINFO" 2>/dev/null) || return
	ve_addresses=$(cat "$VE_STATE_DIR/$VEID" 2>/dev/null) || return
	vzgetnetdev
	for a in $ve_addresses; do
		if ! printf %s "$all_addresses" | grep -Fqw "$a"; then
			vzdelrouting "$a"
			vzarp del "$a"
		fi
	done
}

# If vzctl stop is running -- let it finish the job
ps -o command= -C vzctl 2>/dev/null | \
	grep -Eqw "(stop|restart|chkpnt|suspend) $VEID" && exit 0

I=1
while vzctl --quiet status $VEID | grep -Fw running; do
	sleep $I
	I=$((I+1))
	test $I -gt 10 && exit 1
done

if vzctl --quiet status $VEID | grep -Fw mounted; then
	vzctl --quiet unmount $VEID
fi

# Workaround for Fedora 17, see http://bugzilla.openvz.org/2336
# If $VE_ROOT/reboot file is present, rm it and restart CT
(
	. @PKGCONFDIR@/vz.conf
	. @VPSCONFDIR@/$VEID.conf
	test -f $VE_ROOT/reboot || exit 0
	$(awk '$2 == "'$VE_ROOT'" && $4 !~ "^rw" {
		print "mount -o remount,rw",$1,$2}' /proc/mounts)
	rm -f $VE_ROOT/reboot
	exit 111
)
test $? -eq 111 && exec vzctl --quiet start $VEID

if test -f "$VE_STATE_DIR/$VEID"; then
	clear_ve_net
	rm -f "$VE_STATE_DIR/$VEID"
fi
exit 0
