#!/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
#
#

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

test -f ${VZCONF} || exit 1
test -f @PKGLIBDIR@/scripts/vps-functions || exit 1

. @PKGLIBDIR@/scripts/vps-functions
. ${VZCONF}

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

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


#
# Get list of stopped VEs
#
function 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
}

function get_ip_list()
{
	local veid=$1

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

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

	[ -z "${VEID}" ] && return
	get_ip_list ${VEID}
	vzgetnetdev
	[ -z "${LOGFILE}" ] || echo "`date --iso-8601=seconds`  venetclean : VE $VEID : VE 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}
{
	clear_ve_net ${ve}
	rm -f ${VE_STATE_DIR}/${ve} >/dev/null 2>&1
}

