#!/bin/bash
#
# /etc/init.d/quagga -- start/stop the Quagga routing daemons
#
# Written by Endre Hirling <endre@mail.elte.hu>

PATH=/bin:/usr/bin:/sbin:/usr/sbin
D_PATH=/sbin
C_PATH=/etc/quagga
DAEMONS="zebra bgpd ripd ripngd ospfd ospf6d"


# Pidfile name

pidfile()
{
	echo "/var/run/$1.pid"
}

# Check if daemon is started (by
# checking for the pidfile)

started()
{
	[ -e `pidfile $1` ] && return 0
	return 1
}

# Start the daemon given in the
# parameter, printing its name to the
# terminal

start()
{
	echo -n " $1"
	start-stop-daemon --start --exec "$D_PATH/$1" -- -d
}

# Stop the daemon given in the
# parameter, printing its name to the
# terminal

stop()
{
	if ! started "$1" ; then
		echo -n " ($1)"
		return 0
	else
		echo -n " $1"
		start-stop-daemon --stop --quiet --oknodo --exec "$D_PATH/$1"
		rm -f `pidfile $1`
	fi
}

# Check if the daemon's executable and
# config files are there

check()
{
	[ -x "$D_PATH/$1" ] || return 1
	[ -r "$C_PATH/$1.conf" ] || return 1
	return 0
}

# Check if the daemon is to be run at
# the current priority

checkprio()
{
	cp_tp=${!1}
	[ "$cp_tp" = "no" ] && return 1
	cp_tp="${cp_tp/#yes/10}"
	expr "$cp_tp" '<=' "$prio" >/dev/null 2>&1
	case $? in
		0)
			return 0
		;;
		1)
			return 1
		;;
		2)
			echo "Invalid priority for $D, not starting."
			return 1
		;;
	esac
}

# Stops all daemons not to be run at
# current priority (priority greater
# than current)

stop_prio()
{
	echo -n "Stopping Quagga daemons (prio:$prio):"
	for i in $DAEMONS; do
		if ! checkprio $i ; then
			stop "$i"
		fi
	done
	echo "."
}

# Starts all daemons with priority less
# than the current

start_prio()
{
	echo -n "Flushing Quagga routing tables..."
	ip route flush proto zebra
	echo -n "Starting Quagga daemons (prio:$prio):"
	for i in $DAEMONS; do
		if checkprio $i ; then
			start "$i"
		fi
	done
	echo "."
}

# Main program #

for i in $DAEMONS;do eval "$i=no";done

# Load configuration and check if zebra
# can be started

[ ! -r "$C_PATH/daemons" ] && exit 0
. "$C_PATH/daemons"


# Set priority of un-startable daemons
# to 'no'

for D in $DAEMONS; do
	if ! check $D ; then
		eval "$D=no"
	fi
done


case "$1" in

# Start all daemons if 'start' or priority 10 is given

  start|10)
		prio=${2:-"10"}
		start_prio
  ;;
	
# Stop/start daemons for the appropriate priority level

	[1-9])
		prio="$1"
		stop_prio
		start_prio
	;;

# Stop all daemons at level '0' or 'stop'

  stop|0)
		echo -n "Stopping Quagga daemons:"
		for i in $DAEMONS zebra; do
			stop "$i"
		done
		echo "."
    ;;

	restart|force-reload)
    $0 stop
    sleep 2
    killall -9 zebra
    killall -9 bgpd
    killall -9 ripd
    killall -9 ripngd
    killall -9 ospfd
    killall -9 ospf6d
    rm /var/run/zebra.pid
    rm /var/run/bgpd.pid
    rm /var/run/ripd.pid
    rm /var/run/ripngd.pid
    rm /var/run/ospfd.pid
    rm /var/run/ospf6d.pid
    $0 start
    ;;

	*)
    echo "Usage: /etc/init.d/quagga {start|stop|restart|force-reload|<priority>}"
    exit 1
    ;;
esac

exit 0
