#!/bin/bash
#
# bonding       Bond and unbond network interfaces
#
# chkconfig: 345 11 89
# description: Bonds and unbonds all specified network interfaces on boot
# probe: true

CONFIGDIR=/etc/config.d/bonding
IFENSLAVE=/sbin/ifenslave
IFCONFIG=/sbin/ifconfig

function bond {
    if [ ! -e $CONFIGDIR/$1 ]; then
        echo "Device $1: no configuration file found";
        return 1;
    fi;

    while read line; do
        if [ $($IFCONFIG | grep $line -A 3 | grep SLAVE) -ge 1 ]; then
            echo "Device $1: $line is already a slave";
            continue;
        fi;
        $IFENSLAVE $1 $line;
        echo "Device $1: $line is now a slave";
    done < $CONFIGDIR/$1;

    echo "Device $1: bonded";
};

function unbond {
    if [ ! -e $CONFIGDIR/$1 ]; then
        echo "Device $1: no configuration file found";
        return 1;
    fi;

    while read line; do
        if [ $($IFCONFIG | grep $line -A 3 | grep SLAVE) -le 0 ]; then
            echo "Device $1: $line is not a slave";
            continue;
        fi;
        $IFENSLAVE -d $1 $line;
        echo "Device $1: $line is no longer a slave";
    done < $CONFIGDIR/$1;

    echo "Device $1: unbonded";
};

case $1 in
    start)
        if [ -z $2 ]; then
            for i in `ls -1 /etc/config.d/bonding`; do
                bond $i;
            done;
        else
	    bond $2;
        fi;
    ;;

    stop)
        if [ -z $2 ]; then
            for i in `ls -1 /etc/config.d/bonding`; do
                unbond $i;
            done;
        else
            unbond $2;
        fi;
    ;;

    *)
        echo "Usage: `basename $0` (start|stop) [interface]";
    ;;
esac
