#!/bin/sh

# You don't usually need to touch this file at all, the full configuration
# of the bridge can be done in a standard way on /etc/network/interfaces.

# Have a look at /usr/share/doc/bridge-utils/README.Debian.gz if you want
# more info about the way on wich a bridge is set up on Debian.

if [ ! -x /usr/sbin/brctl ]
then
  exit 0
fi

case "$IF_BRIDGE_PORTS" in
    "")
	exit 0
	;;
    none)
	INTERFACES=""
	;;
    all)
	INTERFACES=`grep eth /proc/net/dev|sed 's/\(\ *\)\(eth[^:]*\)\(.*\)/\2/'`
	;;
    *)
	INTERFACES="$IF_BRIDGE_PORTS"
	;;
esac

brctl addbr $IFACE &&

for i in $INTERFACES
do
  if [ -x /etc/network/if-pre-up.d/vlan ]; then
    env IFACE=$i /etc/network/if-pre-up.d/vlan
  fi
  if [ "$IF_BRIDGE_HW" ]
  then
     ifconfig $i down; ifconfig $i hw ether $IF_BRIDGE_HW
  fi
  brctl addif $IFACE $i && ifconfig $i 0.0.0.0 up
done

if [ "$IF_BRIDGE_AGEING" ]
then
  brctl setageing $IFACE $IF_BRIDGE_AGEING
fi

if [ "$IF_BRIDGE_BRIDGEPRIO" ]
then
  brctl setbridgeprio $IFACE $IF_BRIDGE_BRIDGEPRIO
fi

if [ "$IF_BRIDGE_FD" ]
then
  brctl setfd $IFACE $IF_BRIDGE_FD
fi

if [ "$IF_BRIDGE_GCINT" ]
then
  brctl setgcint $IFACE $IF_BRIDGE_GCINT
fi

if [ "$IF_BRIDGE_HELLO" ]
then
  brctl sethello $IFACE $IF_BRIDGE_HELLO
fi

if [ "$IF_BRIDGE_MAXAGE" ]
then
  brctl setmaxage $IFACE $IF_BRIDGE_MAXAGE
fi

if [ "$IF_BRIDGE_PATHCOST" ]
then
  brctl setpathcost $IFACE $IF_BRIDGE_PATHCOST
fi

if [ "$IF_BRIDGE_PORTPRIO" ]
then
  brctl setportprio $IFACE $IF_BRIDGE_PORTPRIO
fi

if [ "$IF_BRIDGE_STP" ]
then
  brctl stp $IFACE $IF_BRIDGE_STP
fi


ifconfig $IFACE 0.0.0.0 up


if [ "$IF_BRIDGE_MAXWAIT" ]
then
  MAXWAIT=$IF_BRIDGE_MAXWAIT
else
  MAXWAIT=`brctl showstp $IFACE|sed -n 's/^.*forward delay[ 	]*\(.*\)\..*bridge forward delay[ 	]*\(.*\)\..*$/\1 \2/p'`
  if [ "$MAXWAIT" ]
  then
    if [ ${MAXWAIT% *} -gt ${MAXWAIT#* } ]
    then
      MAXWAIT=$((2*(${MAXWAIT% *}+1)))
    else
      MAXWAIT=$((2*(${MAXWAIT#* }+1)))
    fi
  else
    if [ "$IF_BRIDGE_FD" ]
    then
      MAXWAIT=$((2*(${IF_BRIDGE_FD%.*}+1)))
    else
      MAXWAIT=32
    fi
    /bin/echo -e "\nWaiting $MAXWAIT seconds for $IFACE to get ready."
    sleep $MAXWAIT
    MAXWAIT=0
  fi
fi

if [ "$MAXWAIT" != 0 ]
then
  /bin/echo -e "\nWaiting for $IFACE to get ready (MAXWAIT is $MAXWAIT seconds)."

  unset BREADY
  COUNT=0

  while [ ! "$BREADY" -a $COUNT -lt $MAXWAIT ]
  do
    sleep 1
    COUNT=$(($COUNT+1))
    BREADY=true
    for i in `brctl showstp $IFACE|sed -n 's/^.*port id.*state[ 	]*\(.*\)$/\1/p'`
    do
      if [ "$i" != "forwarding" -a "$i" != "blocking" ]
      then
        unset BREADY
      fi
    done
  done

fi
