#!/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=""
	;;
    *)
	INTERFACES="$IF_BRIDGE_PORTS"
	;;
esac

brctl addbr $IFACE &&

for i in $INTERFACES
do
  if [ "$i" = "all" ]; then
    i=$(grep eth /proc/net/dev|sed 's/\(\ *\)\(eth[^:]*\)\(.*\)/\2/')
  fi
  for port in $i
  do
    if [ -x /etc/network/if-pre-up.d/vlan ]; then
      env IFACE=$port /etc/network/if-pre-up.d/vlan
    fi
    if [ "$IF_BRIDGE_HW" ]
    then
       ifconfig $port down; ifconfig $port hw ether $IF_BRIDGE_HW
    fi
    brctl addif $IFACE $port && ifconfig $port 0.0.0.0 up
  done
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
