#! /bin/sh

#
# Called by hnetd in order to control the multicast daemon
# 
# Call syntax:
#
# status
#
# init (start|stop)
#
# rpa (ADDRESS|none) (OLD-ADDRESS|none)
#
# bp ifname (add|remove) ADDRESS PORT
#
# proxy ifname (on|off) [ADDRESS PORT]
#
# pim ifname (on|off)
#

echo "[multicast.script] $*"

error () {
	echo "This script must be run by hnetd."
	exit 1
}

if [ "$(id -u)" -ne "0" ] || [ "$1" = "" ]; then
	error
fi

status () {
	EXE=`which pimbd`
	[ -n "$EXE" ] && exit 0 || exit 1
}

init () {
	if [ -f "/etc/init.d/pimbd" ]; then
		if [ "$1" = "start" ]; then
			/etc/init.d/pimbd restart
		else
			/etc/init.d/pimbd stop
		fi
	else
		if [ -f "/tmp/pimbd-hnet.pid" ]; then
			kill `cat /tmp/pimbd-hnet.pid`
			rm /tmp/pimbd-hnet.pid
		fi
		if [ "$1" = "start" ]; then
			pimbd -S -p /tmp/pimbd-hnet.pid &
		fi
	fi
}

rpa () {
	if [ "$2" != "none" ]; then
	    pimbc rpa flush "$2"
	    pimbc rpa set "$2" rpl_jp off
	fi
	if [ "$1" != "none" ]; then
		pimbc rpa add "$1" "ff00::/8"
		pimbc rpa add "$1" "224.0.0.0/4"
		pimbc rpa set "$1" rpl_jp on
	fi
}

bp () {
	case "$1" in
		add) pimbc proxy add "$2" "$3" ;;
		remove) pimbc proxy del "$2" "$3" ;;
		*) error ;;
	esac
}

proxy () {
	case "$2" in
		on) pimbc link set "$1" proxy "$3" "$4" ;;
		off) pimbc link set "$1" proxy off ;;
		*) error ;;
	esac
}

pim () {
	case "$2" in
		on) pimbc link set "$1" pim on ssbidir on mld on igmp on hello 500ms ;;
		off) pimbc link set "$1" pim off ssbidir off mld off igmp off ;;
		*) error ;;
	esac
}

case "$1" in
	status) shift 1; status $@;;
	init) shift 1; init $@;;
	rpa) shift 1; rpa $@;;
	bp) shift 1; bp $@;;
	proxy) shift 1; proxy $@;;
	pim) shift 1; pim $@;;
	*) error;;
esac

exit 0;