#!/bin/sh
#  Copyright (C) 2000-2008, 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
#
#

VZCONF=/etc/vz/vz.conf
VEINFO=/proc/vz/veinfo
VES_INFO=
VE_RUN=
VE_PREV=

test -f "$VZCONF" || exit 1
test -f /usr/lib64/vzctl/scripts/vps-functions || exit 1

. /usr/lib64/vzctl/scripts/vps-functions
. "$VZCONF"

#
# Get the list of currently running containers
#
get_run_ve()
{
	VE_RUN=`echo "$VES_INFO" | awk '$1 != 0 {print $1}'`
}

#
# Get the list of started containers by vzctl
#
get_prev_ve()
{
	[ -d "$VE_STATE_DIR" ] || return
	VE_PREV=`ls "$VE_STATE_DIR" | grep -w -e "[0-9]*" 2>/dev/null`
}


#
# Get the list of stopped containers
#
get_stopped_ve()
{
	get_run_ve
	get_prev_ve

	if [ -z "$VE_RUN" ]; then
		VE_STOPPED="$VE_PREV"
	else
		VE_STOPPED=`echo -e "$VE_PREV" | grep -w -v "$VE_RUN"`
	fi
}

get_ip_list()
{
	local veid=$1

	IP_ADDR=
	[ -n "$veid" ] || return
	[ -f "$VE_STATE_DIR/$veid" ] || return
	IP_ADDR=`cat "$VE_STATE_DIR/$veid"`
}

clear_ve_net()
{
	local ip
	VEID="$1"

	[ -n "$VEID" ] || return
	get_ip_list "$VEID"
	vzgetnetdev
	[ -z "$LOGFILE" ] ||
		echo "`date --iso-8601=seconds` venetclean : CT $VEID : CT died, clear IPs: $IP_ADDR" >> "$LOGFILE"
	for ip in $IP_ADDR; do
		# clear IP if not used
		if ! echo -e "$VES_INFO" | grep -w "$ip" >/dev/null 2>&1; then
			vzdelrouting "$ip"
			vzarp del "$ip"
		fi
	done
}

# If VZ is not running -- do nothing
# Fix for OpenVZ bug #107
test -f "$VEINFO" || exit 0

VES_INFO=`cat "$VEINFO" 2>/dev/null` || exit
get_stopped_ve
for ve in $VE_STOPPED; do
	clear_ve_net "$ve"
	rm -f "$VE_STATE_DIR/$ve" >/dev/null 2>&1
done

exit 0
