#!/bin/sh

BABEL_EXE=`which babeld`
BABEL_PID=/var/run/babeld-hnetd.pid
ISIS_INIT=`which autoisis`

# Routing table for BFS (also rule priority)
BFSTABLE=33333
BFSPROTO=73

act=$1
shift

case "$act" in
configure)
	if [ -x "$BABEL_EXE" ]; then
		[ -f $BABEL_PID ] && kill -9 `cat $BABEL_PID`
		#start-stop-daemon -K -q -t -x $BABEL_EXE -p $BABEL_PID

		if [ -n "$1" ]; then
			#start-stop-daemon -S -x $BABEL_EXE -- `echo $BABEL_ARGS` $*
			rm -f $BABEL_PID
			$BABEL_EXE -D -I $BABEL_PID \
				-C "redistribute" \
				-C "redistribute local deny" \
				$*

			# Wait for pid file to actually show up
			[ -f $BABEL_PID ] || sleep 1
			[ -f $BABEL_PID ] || sleep 2
			[ -f $BABEL_PID ] || sleep 4
		fi
	elif [ -x "$ISIS_INIT" ]; then
		if [ -z "$1" ]; then
			$ISIS_INIT stop
		else
			$ISIS_INIT start "$@"
		fi
	else
		exit 1
	fi
	;;

bfsprepare)
	ip -6 rule del table "$BFSTABLE" priority "$BFSTABLE"
	ip -4 rule del table "$BFSTABLE" priority "$BFSTABLE"
	ip -6 rule add table "$BFSTABLE" priority "$BFSTABLE"
	ip -4 rule add table "$BFSTABLE" priority "$BFSTABLE"
	ip -6 route flush table "$BFSTABLE" proto $BFSPROTO
	ip -4 route flush table "$BFSTABLE" proto $BFSPROTO
	ip -6 route flush proto "$BFSPROTO"
	;;

bfsipv6assigned)
	if grep -q chaos /etc/openwrt_release; then
		exec ip -6 route add "$1" via "$2" dev "$3" metric "$4" table "$BFSTABLE" proto "$BFSPROTO"
	# IPv6 throw routes are broken in current Linux kernels...
	else
		exec ip -6 route add "$1" via "$2" dev "$3" metric "$((2140000000+$4))" proto "$BFSPROTO"
	fi
	;;

bfsipv4assigned)
	exec ip -4 route add "$1" via "$2" dev "$3" metric "$4" table "$BFSTABLE" proto "$BFSPROTO" onlink
	;;

bfsipv6prefix)
	exec ip -6 route add throw "$1" proto $BFSPROTO metric 2147483645
	;;
	
bfsipv6uplink)
	ip -6 route add "$5" via "$2" dev "$3" metric "$4" table "$BFSTABLE" proto "$BFSPROTO" from ::/128
	exec ip -6 route add "$5" via "$2" dev "$3" metric "$4" table "$BFSTABLE" proto "$BFSPROTO" from "$1"
	;;

bfsipv4prefix)
	exec ip -4 route add throw "$1" proto $BFSPROTO metric 2147483645
	;;
	
bfsipv4uplink)
	exec ip -4 route add "$5" via "$2" dev "$3" metric "$4" table "$BFSTABLE" proto "$BFSPROTO" onlink
	;;

esac
