#!/bin/sh

[ -z "$2" ] && echo "Error: should be run by hnetd" && exit 1

action="$1"
proto="$2"
shift 2

BABEL_EXE=/usr/sbin/babeld
BABEL_PID=/var/run/babeld-hnetd.pid
BABEL_ARGS="-D -I $BABEL_PID "\
"-C redistribute ip 0.0.0.0/0 eq 0 proto 3 metric 128 "\
"-C redistribute ip 0.0.0.0/0 eq 0 metric 128 "\
"-C redistribute ip ::/0 eq 0 metric 128 "\
"-C redistribute eq 64 "
ISIS_INIT=/usr/sbin/autoisis

case "$action" in
	enumerate)
		## echo PROTOCOL-ID PREFERENCE
		## need at least fallback to qualify as router
		echo 0 0
		## check babel
		[ -x "$BABEL_EXE" ] && echo 1 128
		## check IS-IS
		[ -x "$ISIS_INIT" ] && echo 3 128
	;;
	enable|reconfigure|disable)
		case "$proto" in
			1)
                                [ -f $BABEL_PID ] && kill -9 `cat $BABEL_PID`
	                        #start-stop-daemon -K -q -t -x $BABEL_EXE -p $BABEL_PID

				if [ "$action" != "disable" -a -n "$1" ]; then
				    #start-stop-daemon -S -x $BABEL_EXE -- `echo $BABEL_ARGS` $*
                                    rm -f $BABEL_PID
                                    $BABEL_EXE `echo $BABEL_ARGS` $*
                                    # Wait for pid file to actually show up
                                    [ -f $BABEL_PID ] || sleep 1
                                    [ -f $BABEL_PID ] || sleep 2
                                    [ -f $BABEL_PID ] || sleep 4
				fi 
			;;
			3)
				if [ "$action" = "disable" -o -z "$1" ]; then
					$ISIS_INIT stop
				else
					$ISIS_INIT start "$@"
				fi
			;;
			*)
				exit 1;
			;;
		esac
		exit 0;
	;;
esac
