#!/bin/bash
#
# Add virtual network interfaces (veth's) in a container to a bridge on CT0

CONFIGFILE=@PKGCONFDIR@/conf/$VEID.conf
. $CONFIGFILE

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

if [ ! -n "$NETIFLIST" ]; then
   echo "According to $CONFIGFILE, CT$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 CT0 for CT$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
