#! /bin/sh

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/sbin/olsrd
NAME="olsr.org"
DESC="OLSR routing protocol daemon"

test -x $DAEMON || exit 0

test "noshape" != "$2" && DEVICES=$(sed -n -e"s/^[ \t]*Interface//;tp;b;:p;p" /etc/olsrd.conf)
MODULES="cls_u32 sch_prio sch_sfq"

case "$1" in
  start)
	echo "Starting $DESC: $NAME"
	test -e /usr/sbin/olsrd-clearroutes && /usr/sbin/olsrd-clearroutes
	start-stop-daemon -S -x $DAEMON -- -d 0;
	if [ -n "$DEVICES" ]; then
		echo "Starting olsr shaping..."
		for i in $MODULES; do
			insmod $i
		done
		for DEV in $DEVICES; do
			eval DEV=$DEV
			if lsmod|grep -q ^hostap;then
				test "wlan0" = "$DEV" && DEV=wifi0
				test "wlan1" = "$DEV" && DEV=wifi1
			fi
			tc qdisc add dev $DEV root handle 1: prio
			tc qdisc add dev $DEV parent 1:1 handle 10: sfq
			tc filter add dev $DEV protocol ip parent 1:0 prio 1 u32 match ip dport 698 0xffff flowid 10:1
			tc filter add dev $DEV protocol ip parent 1:0 prio 2 u32 match ip dst 0.0.0.0/0 flowid 10:2
		done
	fi
	echo "done."
	;;
  stop)
	if [ -n "$DEVICES" ]; then
		echo "Stopping olsr shaping..."
		for DEV in $DEVICES; do
			eval DEV=$DEV
			if lsmod|grep -q ^hostap;then
				test "wlan0" = "$DEV" && DEV=wifi0
				test "wlan1" = "$DEV" && DEV=wifi1
			fi
			tc filter del dev $DEV protocol ip parent 1:0 prio 2 u32 match ip dst 0.0.0.0/0 flowid 10:2
			tc filter del dev $DEV protocol ip parent 1:0 prio 1 u32 match ip dport 698 0xffff flowid 10:1
			tc qdisc del dev $DEV parent 1:1 handle 10: sfq
			tc qdisc del dev $DEV root handle 1: prio
		done
		for i in $MODULES; do
			rmmod $i
		done
	fi
	echo "Stopping $DESC: $NAME "
	start-stop-daemon -K -x $DAEMON
	test -e /usr/sbin/olsrd-clearroutes && /usr/sbin/olsrd-clearroutes
	echo "done."
	;;
  restart|force-reload)
	echo "restarting $DESC: $NAME "
	$0 stop noshape
	sleep 5
	$0 start noshape
	exit;
	;;
  *)
	echo "Usage: /etc/init.d/$NAME {start|stop|restart}" >&2
	exit 1
	;;
esac

exit 0
