#!/bin/sh +x

# $1: tap name
# $2: interface name could be eth0 or bridge name

if [ "x$2" = "x" ];then
    NETMASK=""
else
    NETMASK=`ifconfig $2 | grep "inet " | awk '{print $4}' | cut -d : -f2`
fi
GW=`netstat -rn | grep ^0.0.0.0 | awk '{print $2}'`
BR=bridge1
echo "NETMASK: $NETMASK"
echo "GW: $GW"
echo "Check if bridge interface exists."
echo "CHECK_BR=`/bin/ls /sys/class/net | grep $BR`"
CHECK_BR=`/bin/ls /sys/class/net | grep $BR`
if [ "x$CHECK_BR" = "x" ]
then
    echo "$BR does not exist! create it"
    BASEIPADDR=`ip addr show eth0 | awk '/inet / {print $2}' | cut -d/ -f1`
    brctl addbr $BR
else
    BASEIPADDR=`ip addr show $BR | awk '/inet / {print $2}' | cut -d/ -f1`
fi
echo "BASEIPADDR: $BASEIPADDR"
echo  "ifconfig up $1 device."
ifconfig $1 0.0.0.0 promisc up

if [ "$2" != "" ] && [ "$2" != "$BR" ]
then
    echo "Take down $2."
    ip addr flush dev $2

    echo "Add tap device and interface to bridge."
    brctl addif $BR $2
fi
brctl addif $BR $1

echo "Add the default route."
if [ "x$NETMASK" = "x" ];then
    echo "netmask is NULL"
    echo "ifconfig $BR $BASEIPADDR"
    ifconfig $BR $BASEIPADDR
else
    echo "ifconfig $BR $BASEIPADDR netmask $NETMASK"
    ifconfig $BR $BASEIPADDR netmask $NETMASK
fi
NET=`netstat -rn | grep ^0.0.0.0 | awk '{print $8}'`
echo "NET: $NET"
if [ "$NET" != "$BR" ]
then
    echo "route add default gw $GW"
    route add default gw $GW
fi
exit 0
