#!/bin/sh -x
#$1 = tap name (e.g. tap0)
#$2 = bridge name (optional)
TAP=$1
echo "TAP: $1"

BRIDGE=""
if [ x"$2" != x ]; then
    echo "BRIDGE=$2"
    BRIDGE=$2
else
    echo "BRIDGE=bridge1"
    BRIDGE=bridge1
fi

BASE=en0
echo "get base network information"
IP=`ipconfig getifaddr $BASE`
NETMASK=`ifconfig $BASE | grep "inet " | awk '{print $4}'`
GW=`netstat -rn | grep $BRIDGE | grep ^default | awk '{print $2}'`
echo "IP: $IP"
echo "NETMASK: $NETMASK"
echo "GW: $GW"

echo "create bridge interface"
CHECK_BR=`ifconfig | grep ^$BRIDGE:`
echo "CHECK_BR: $CHECK_BR"
if [ "$CHECK_BR" = "" ]
then
    ifconfig $BRIDGE create
fi

echo "add base network and tap device to bridge"
ifconfig $BRIDGE addm $BASE
ifconfig $BRIDGE addm $TAP
ifconfig $BRIDGE up

echo "set IP of base network to bridge"
ifconfig $BASE delete $IP
ifconfig $BRIDGE $IP netmask $NETMASK

echo "change network interface of default gateway"
NET=`netstat -rn | grep ^default | awk '{print $6}'`
if [ $NET != $BRIDGE ];then
    echo "route change default $GW"
    route change default $GW
fi
