#!/bin/bash
# /usr/sbin/vznetaddbr
# a script to add virtual network interfaces (veth's) in 
# a VE to a bridge on VE0

CONFIGFILE=/etc/vz/conf/$VEID.conf
. $CONFIGFILE

NETIFLIST=`echo $NETIF | sed 's/;/\n/g'`

if [ ! -n "$NETIFLIST" ]; then
   echo "According to $CONFIGFILE VE$VEID has no veth interface configured."
   exit 1
fi

IFACES=`echo $NETIFLIST | sed 's/;/\n/g'`
for tmp in $IFACES; do 
    CTIFNAME=
    CTBRIDGE=
    VZHOSTIF=

    NETIF_OPTIONS=`echo $tmp | sed 's/,/\n/g'`
    for str in $NETIF_OPTIONS; do 
        # getting 'ifname' parameter value
        if [[ "$str" =~ "^ifname=" ]]; then
            # remove the parameter name from the string (along with '=')
	    CTIFNAME=${str#*=};
        fi
        if [[ "$str" =~ "^bridge=" ]]; then
            # remove the parameter name from the string (along with '=')
	    CTBRIDGE=${str#*=};
        fi
        # getting 'host_ifname' parameter value
        if [[ "$str" =~ "^host_ifname=" ]]; then
            # remove the parameter name from the string (along with '=')
	    VZHOSTIF=${str#*=};
        fi
    done

    if [[ "$VZHOSTIF" != "$3" ]]; then
	continue 
    fi
    if [ ! -n "$CTBRIDGE" ]; then
	CTBRIDGE=vmbr0
    fi

    echo "Adding interface $VZHOSTIF to bridge $CTBRIDGE on VE0 for VE$VEID"
    /sbin/ifconfig $VZHOSTIF 0
    echo 1 > /proc/sys/net/ipv4/conf/$VZHOSTIF/proxy_arp
    echo 1 > /proc/sys/net/ipv4/conf/$VZHOSTIF/forwarding
    /usr/sbin/brctl addif $CTBRIDGE $VZHOSTIF

    break
done

exit 0
