#!/bin/sh
#
#  Bond the wireless to the wired interface.

#  abort if no ifenslave
if ! which ifenslave >/dev/null
then
	[ "$WIFIROAMD_VERBOSE_LEVEL" -gt 0 ] && \
		logger -t wifiroamd_bonding "ifenslave not found, disabling bonding."
	WIFIROAMD_BONDING_ENABLED=0
	exit 0
fi

if [ "$WIFIROAMD_BONDING_WITH_DEVICE" = auto ]
then
	[ "$WIFIROAMD_VERBOSE_LEVEL" -gt 0 ] && \
		logger -t wifiroamd_bonding "Looking for bonding device name."
	WIFIROAMD_BONDING_WITH_DEVICE=""
	for TESTDEV in /sys/class/net/eth*
	do
		TESTDEV=`basename "$TESTDEV"`
		[ "$TESTDEV" = "$WIFIROAMD_DEVICE" ] && continue
		WIFIROAMD_BONDING_WITH_DEVICE="$TESTDEV"
		[ "$WIFIROAMD_VERBOSE_LEVEL" -gt 2 ] && \
			logger -t wifiroamd_bonding "Auto-located bonding device '$TESTDEV'"
		break
	done
fi

#  IP address must be specified
if [ -z "$WIFIROAMD_BONDING_IPADDRESS" ]
then
	[ "$WIFIROAMD_VERBOSE_LEVEL" -gt 0 ] && \
		logger -t wifiroamd_bonding "Bonding disabled because " \
			"WIFIROAMD_BONDING_IPADDRESS is not set."
	WIFIROAMD_BONDING_ENABLED=0
	exit 0
fi

#  gateway must be specified
if [ -z "$WIFIROAMD_BONDING_GATEWAY" ]
then
	[ "$WIFIROAMD_VERBOSE_LEVEL" -gt 0 ] && \
		logger -t wifiroamd_bonding "Bonding disabled because " \
			"WIFIROAMD_BONDING_GATEWAY is not set."
	WIFIROAMD_BONDING_ENABLED=0
	exit 0
fi

#  device is blank, disabled
if [ -z "$WIFIROAMD_BONDING_WITH_DEVICE" ]
then
	[ "$WIFIROAMD_VERBOSE_LEVEL" -gt 0 ] && \
		logger -t wifiroamd_bonding "Bonding disabled, please specify a " \
			"device name to enable"
	WIFIROAMD_BONDING_ENABLED=0
	exit 0
fi

modprobe bonding miimon=100 use_carrier=1 mode=active-backup \
		primary="$WIFIROAMD_BONDING_WITH_DEVICE"
ip addr add "$WIFIROAMD_BONDING_IPADDRESS" dev bond0
ifconfig bond0 up
ifconfig "$WIFIROAMD_DEVICE" 0.0.0.0
ifconfig "$WIFIROAMD_DEVICE" up
ifenslave bond0 "$WIFIROAMD_DEVICE"
ifconfig "$WIFIROAMD_BONDING_WITH_DEVICE" 0.0.0.0
ifconfig "$WIFIROAMD_BONDING_WITH_DEVICE" up
ifenslave bond0 "$WIFIROAMD_BONDING_WITH_DEVICE"
route add default gw "$WIFIROAMD_BONDING_GATEWAY"
WIFIROAMD_BONDING_ENABLED=1
WIFIROAMD_DHCP_INTERFACE="bond0"
