#!/bin/sh

IFENSLAVE=/sbin/ifenslave
IFSTATE=/etc/network/run/ifstate
BOND_PARAMS=/sys/class/net/"$IFACE"/bonding/

if [ ! -x $IFENSLAVE ] ; then
	exit 0
fi


add_master()
{
    if [ ! -r /sys/class/net/bonding_masters ]; then
        modprobe bonding >/dev/null 2>&1 || true
    fi

    if ! grep -sq "\\<$IFACE\\>" /sys/class/net/bonding_masters; then
        echo "+$IFACE" > /sys/class/net/bonding_masters
    fi
}


case "$IF_SLAVES" in
	"")
		exit 0
		;;
	none)
		INTERFACES=""
		;;
	all)
		INTERFACES=`grep eth /proc/net/dev|sed 's/\(\ *\)\(eth[^:]*\)\(.*\)/\2/'`
		AUTOIF="yes"
		;;
	*)
		INTERFACES="$IF_SLAVES"
		;;
esac


if [ -n "$INTERFACES" ] ; then
		add_master

		if [ "$IF_BOND_MODE" ]; then
			echo "$IF_BOND_MODE" > $BOND_PARAMS/mode
	        fi
		if [ "$IF_BOND_MIIMON" ]; then
			echo "$IF_BOND_MIIMON" > $BOND_PARAMS/miimon
	        fi
		if [ "$IF_BOND_UPDELAY" ]; then
			echo "$IF_BOND_UPDELAY" > $BOND_PARAMS/updelay
	        fi
		if [ "$IF_BOND_DOWNDELAY" ]; then
			echo "$IF_BOND_DOWNDELAY" > $BOND_PARAMS/downdelay
	        fi
		if [ "$IF_BOND_ARP_IP_TARGET" ]; then
			for target in $IF_BOND_ARP_IP_TARGET; do
				echo "+$target" > $BOND_PARAMS/arp_ip_target
			done
	        fi
		if [ "$IF_BOND_ARP_INTERVAL" ]; then
			echo "$IF_BOND_ARP_INTERVAL" > $BOND_PARAMS/arp_interval
	        fi
		if [ "$IF_BOND_XMIT_HASH_POLICY" ]; then
			echo "$IF_BOND_XMIT_HASH_POLICY" > $BOND_PARAMS/xmit_hash_policy
	        fi
		if [ "$IF_BOND_LACP_RATE" ]; then
			echo "$IF_BOND_LACP_RATE" > $BOND_PARAMS/lacp_rate
	        fi
		ifconfig "$IFACE" up
		for slave in $INTERFACES ; do
				if ( [ "$AUTOIF" ] && grep -q "^$slave=" $IFSTATE ) ; then
					echo "Not enslaving interface $slave since it is already configured"
				else
					ifconfig "$slave" down
					$IFENSLAVE "$IFACE" "$slave"
				fi
		done
		if [ "$IF_BOND_PRIMARY" ]; then
			echo "$IF_BOND_PRIMARY" > $BOND_PARAMS/primary
	        fi
fi
