#!/bin/sh
RC_SCRIPT=/usr/local/etc/rc.d/quagga.sh
QUAGGA_CONFIG_BASE=/var/etc/quagga

ZEBRA_CONFIG=${QUAGGA_CONFIG_BASE}/zebra.conf
ZEBRA_PORT=2601
ZEBRA_PASSWORD=`/usr/bin/grep '^password ' ${ZEBRA_CONFIG} | /usr/bin/awk '{print $2};'`

OSPF_CONFIG=${QUAGGA_CONFIG_BASE}/ospfd.conf
OSPF_PORT=2604
OSPF_PASSWORD=`/usr/bin/grep '^password ' ${OSPF_CONFIG} | /usr/bin/awk '{print $2};'`

daemon_command() {
	COMMANDS=${2}
	COMMANDS=${COMMANDS}`echo -e "\n${3}\n"`
	COMMANDS=${COMMANDS}`echo -e "\nexit\n"`
	echo "$COMMANDS" | /usr/bin/nc localhost ${1} | /usr/bin/tail -n +10 | sed '$d'
}

case $1 in
stop)
	$RC_SCRIPT stop
	;;
start)
	$RC_SCRIPT start
	;;
restart)
	$RC_SCRIPT restart
	;;
zebra)
	if [ "`pgrep zebra`" = "" ]; then
		echo "zebra does not appear to be running"
		exit 1
	fi
	case $2 in
	cpu*)
		daemon_command ${ZEBRA_PORT} ${ZEBRA_PASSWORD} "show thread cpu"
		;;
	mem*)
		shift; shift;
		daemon_command ${ZEBRA_PORT} ${ZEBRA_PASSWORD} "show memory $*"
		;;
	int*)
		daemon_command ${ZEBRA_PORT} ${ZEBRA_PASSWORD} "show interface $3"
		;;
	rou*)
		daemon_command ${ZEBRA_PORT} ${ZEBRA_PASSWORD} "show ip route"
		;;
	esac ;;
ospf*)
	if [ "`pgrep ospfd`" = "" ]; then
		echo "ospfd does not appear to be running"
		exit 1
	fi
	case $2 in
	cpu*)
		daemon_command ${OSPF_PORT} ${OSPF_PASSWORD} "show thread cpu"
		;;
	mem*)
		shift; shift;
		daemon_command ${OSPF_PORT} ${OSPF_PASSWORD} "show memory $*"
		;;
	gen*)
		daemon_command ${OSPF_PORT} ${OSPF_PASSWORD} "show ip ospf"
		;;
	nei*)
		shift; shift;
		daemon_command ${OSPF_PORT} ${OSPF_PASSWORD} "show ip ospf neighbor $*"
		;;
	dat*)
		shift; shift;
		daemon_command ${OSPF_PORT} ${OSPF_PASSWORD} "show ip ospf database $*"
		;;
	int*)
		daemon_command ${OSPF_PORT} ${OSPF_PASSWORD} "show ip ospf interface $3"
		;;
	bor*)
		daemon_command ${OSPF_PORT} ${OSPF_PASSWORD} "show ip ospf border-routers"
		;;
	rou*)
		daemon_command ${OSPF_PORT} ${OSPF_PASSWORD} "show ip ospf route"
		;;
	esac ;;
esac