#!/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"
	else
		br=`virsh net-info "$2" | awk '/Bridge:/{print $2}'`
		if [ -z "$br" ]; then
			echo "Cannot find bridge interface for $2 network"
			exit 1
		fi
	fi

	for i in `ls -1 /sys/class/net/$br/brif 2>/dev/null`; do
		if [ ! -d " /sys/class/net/$br/brif/$i" ]; then
			bound_iface=$i
			break;
		fi
	done

	# 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

	if [ "$VPORT_TYPE" = "ovs" ]; then
		ovs-vsctl --may-exist add-port "$br" "$iface"
	else
		brctl addif "$br" "$iface"
	fi
	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

	if [ "$VPORT_TYPE" = "ovs" ]; then
		ovs-vsctl --if-exists del-port "$iface"
	fi
	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
