#!/bin/sh
#
# Tiny tool to help setting up and tearing down bridge devices
# automagically.   Author: <btoedtmann@iem.uni-due.de>
#
# Usage: this is a wrapper for brctl.  Call it instead of brctl
# - if you do a 'autobrctl addif <bridge> <interface>' and
# <bridge> does not exist yet, autobrctl will first issue
# a 'brctl addbr <bridge>'.   When the last connected interface
# is removed from a bridge with 'autobrctl delif <bridge>
# <interface>', autobrctl will finally call 'brctl delbr <bridge>'.
#
# Requirements: bash, grep, awk
#
# Tested with kernel-2.6 and bridge-utils-1.0.6
#

# If bridge device does not exist yet, ('brctl show' will tell us),
# set it up.
if [ x$1 = "xaddif" ]; then
	if ( ! brctl show | grep -Eq "^$2"); then
		brctl addbr $2
		ifconfig $2 up
	fi
fi
brctl $*

# If this was the last interface on the bridge, destroy it.
if [ x$1 = "xdelif" ]; then
	if (brctl show | grep -E "^$2" | awk '{print $4}' | grep -q "^can't"); then 
		ifconfig $2 down
		brctl delbr $2
	fi
fi
