#!/bin/sh

# your IP address
HOST_IP="192.168.0.3"

# netmask
HOST_NETMASK="255.255.255.0"

# your internet gateway
HOST_GATEWAY="192.168.0.1"

# internet interface
HOST_IFACE="eth0"

# name of the bridge
UML_BRIDGE="br0"

# the syntax of UML_IFACES is as follows:
# UML_IFACES="<iface1>:<user1>[ <iface2>:<user2>[...]]"
#
# for instance you have two UMLs, the first runs as user 'tom'
# and the second as 'uml':
#      UML_IFACES="tap1:tom tap2:uml"
UML_IFACES="tap1:uml"

###############

if [ "x$1" = "x-v" ]; then
	VERBOSE=1
	shift
else
	VERBOSE=0
fi

e() { test $VERBOSE = 1 && echo $@; $@; }

case "$1" in
	start)
		echo -n "Setting up UML bridge"
		test $VERBOSE = 1 && echo

		# set up the bridge
		e ifconfig $HOST_IFACE 0.0.0.0 promisc up
		e brctl addbr $UML_BRIDGE
		e brctl setfd $UML_BRIDGE 0
		e brctl sethello $UML_BRIDGE 0
		e brctl stp $UML_BRIDGE off

		# add the host interface
		e ifconfig $UML_BRIDGE $HOST_IP netmask $HOST_NETMASK up
		e route add default gw $HOST_GATEWAY
		e brctl addif $UML_BRIDGE $HOST_IFACE

		# and the UML interface(s)
		for ITMP in $UML_IFACES; do
			IFACE=`echo $ITMP | cut -d ':' -f 1`
			IUSER=`echo $ITMP | cut -d ':' -f 2`
			test `echo $ITMP | grep ':'` || IUSER=root
			e tunctl -u $IUSER -t $IFACE > /dev/null
			e ifconfig $IFACE 0.0.0.0 promisc up
			e brctl addif $UML_BRIDGE $IFACE
			echo -n " $IFACE"
		done

		echo "."
		;;
	stop)
		echo -n "Removing UML bridge"
		test $VERBOSE = 1 && echo

		e ifconfig $UML_BRIDGE down
		e brctl delif $UML_BRIDGE $HOST_IFACE
		for ITMP in $UML_IFACES; do
			IFACE=`echo $ITMP | cut -d ':' -f 1`
			e brctl delif $UML_BRIDGE $IFACE
			e tunctl -d $IFACE > /dev/null
			echo -n " $IFACE"
		done
		e brctl delbr $UML_BRIDGE
		e ifconfig $HOST_IFACE $HOST_IP netmask $HOST_NETMASK up
		e route add default gw $HOST_GATEWAY

		echo "."
		;;
	reload | force-reload | restart)
		$0 stop
		$0 start
		;;
	*)
		echo "Usage: $0 {start|stop|restart}"
esac
