#!/bin/sh
#
# PROVIDE: lvrouted
# REQUIRE: netif routing
# KEYWORD: nojail

lvrouted_enable=${lvrouted_enable:-"NO"}
lvrouted_flags=${lvrouted_flags:-}

. /etc/rc.subr

name="lvrouted"
rcvar=`set_rcvar`
load_rc_config $name

command="/usr/local/sbin/${name}"
pid_file="/var/run/${name}.pid" 

# Import proxies
wleiden_conf="/usr/local/etc/wleiden.conf"
if [ -r $wleiden_conf ]; then
  . ${wleiden_conf}
fi

# If there are proxies specified, them add them with the z flag
if [ -n "$PROXIES" ]; then
  PROXIES=`echo ${PROXIES} | sed 's/\ /\,/g'`
  lvrouted_flags="$lvrouted_flags -z $PROXIES"
fi

start_precmd="lvrouted_flush_routes"

# XXX: Needs to be a flag to disable
# XXX: lvrouted should mark their added routed protocol specific (see: man 8 route)
# lvrouted requires no route to exists before start as it is not able to alter
# old routes, so make it flush all dynamic generated routes
lvrouted_flush_routes() {
	
	# XXX: Does the looping bug still exists?
	# Keep looping till we whiped _all_ dynamic generated routes
	while true; do
		netstat -nr -f inet | awk '{if ($3 ~ /.*D.*/) { exit 1} }'
		if [ $? -eq 0 ]; then
			break
		fi
		echo "WARNING: Flushing all existing DYNAMIC routes" 1>&2
		netstat -nr -f inet | awk '{if ($3 ~ /.*D.*/) {print $1} }' | xargs -n 1 route delete
	done
} 
	
run_rc_command "$1"

