#!/bin/bash
# Copyright (c) 1999-2017, Parallels International GmbH
# Copyright (c) 2017-2019 Virtuozzo International GmbH. All rights reserved.
#
# This file is part of OpenVZ libraries. OpenVZ is free software; you can
# redistribute it and/or modify it under the terms of the GNU Lesser 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
#
# Our contact details: Virtuozzo International GmbH, Vordergasse 59, 8200
# Schaffhausen, Switzerland.
VZNETCFG='/etc/vz/vznet.conf'

[ -f "$VZNETCFG" ] && . "$VZNETCFG"

usage()
{
	echo "vznetcfg addif <dev> <network>"
}

addif()
{
	local iface=$1
	local br
	local bound_iface
	local iface_params

	if [ "$NETWORK_TYPE" = "bridge" ]; then
		br=$2

		for i in `ls -1 /sys/class/net/$br/brif`; do
			if [ ! -d " /sys/class/net/$br/brif/$i" ]; then
				iface_params=$i
				break;
			fi
		done
	else
		br=`prlsrvctl net info "$2" --no-slave || prlsrvctl net info "$2"`
		if [ $? -ne 0 ]; then
			exit 1
		fi

		bound_iface=`echo "$br" | awk '/Bound To:/{print $3}'`
		br=`echo "$br" | awk '/Bridge:/{print $2}'`
		if [ -z "$br" ]; then
			br="$2"
		fi
	fi

	# propagate params
	if [ -n "$bound_iface" ]; then
		iface_params=$(ethtool -k $bound_iface | awk '
			/^rx-checksumming:/{print "rx", $2};
			/^tx-checksumming:/{print "tx", $2};
			/^scatter-gather:/{print "sg", $2};
			/^tcp-segmentation-offload:/{print "tso", $2};
			/^generic-segmentation-offload:/{print "gso", $2}')
		if [ -z "$iface_params" ]; then
			echo "Unable to get $bound_iface ethtool params"
		else
			ethtool -K $iface $iface_params
		fi
	fi

	brctl addif $br $iface
	if [ $? -ne 0 ]; then
		echo "Unable to attach $iface to bridge $br/$2"
		exit 1
	fi

	ip l s dev $iface up
}

delif()
{
	local iface=$1
	local br

	for br in `ls -1 /sys/class/net`; do
		[ -d  /sys/class/net/$br/bridge ] || continue
		brctl show $br | grep -w $iface && brctl delif $br $iface
	done
}

# Call the external script if defined
if [ -n "$EXTERNAL_SCRIPT" -a -x "$EXTERNAL_SCRIPT" ]; then
        export VEID
        exec "$EXTERNAL_SCRIPT" $@
fi

case "$1" in
	addif)
		if test $# -ne 3; then
			usage
			exit 1
		fi

		delif "$2"
		addif "$2" "$3"
	;;
	delif)
		delif "$2"
	;;
	*)
		echo "invalid action"
		exit 1
	;;
esac

exit 0
