#!/bin/sh

PATH=/usr/bin:/usr/sbin:/bin:/sbin
BABEL_EXE=`which babeld`
BABEL_PID=/var/run/babeld-hnetd.pid
BABEL_CONF=/var/run/babeld-hnetd.conf
BABEL_CONF_OWRT=/tmp/babeld.d/hnetd.conf

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

act=$1
shift

create_babel_conf() {
    FILE=$1
    shift
    echo "redistribute" > $FILE
    echo "redistribute local deny" >> $FILE
    echo "ipv6-subtrees yes" >> $FILE
    echo "reflect-kernel-metric true" >> $FILE
    for IF in $*; do
        echo "interface $IF" >> $FILE
    done
}

handle_babel_openwrt() {
    if [ -z "$1" ]; then 
        /etc/init.d/babeld stop
        return
    fi
    mkdir -p `dirname $BABEL_CONF_OWRT`
    create_babel_conf $BABEL_CONF_OWRT $*
    /etc/init.d/babeld restart
}

handle_babel_generic() {
    [ -f $BABEL_PID ] && kill -9 `cat $BABEL_PID`
    if [ -z "$1" ]; then return ; fi
    create_babel_conf $BABEL_CONF $*
    rm -f $BABEL_PID
    $BABEL_EXE -D -I $BABEL_PID -c $BABEL_CONF
    
    # Wait for pid file to actually show up
    [ -f $BABEL_PID ] || sleep 1
    [ -f $BABEL_PID ] || sleep 2
    [ -f $BABEL_PID ] || sleep 4
}

case "$act" in
configure)
	if [ -x "$BABEL_EXE" ]; then
            if [ -f /etc/openwrt_version ] ; then
                handle_babel_openwrt $*
            else 
                handle_babel_generic $*
            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)
	exec ip -6 route add "$1" via "$2" dev "$3" metric "$4" table "$BFSTABLE" proto "$BFSPROTO"
	# IPv6 throw routes are broken in historic Linux kernels...
        # (this workaround plays havoc with e.g. Babel though)
	#exec ip -6 route add "$1" via "$2" dev "$3" metric "$((2140000000+$4))" proto "$BFSPROTO"
	;;

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
