#!/bin/sh /etc/rc.common
# Copyright (C) 2007 OpenWrt.org

START=90

start() {
	# check if the daemon is disabled
	if [ "`/sbin/uci -P/var/state -q get ibrdtn.disable`" == "1" ]; then
		/bin/echo "dtnd is disabled"
		return
	fi
	
	/bin/echo -n "running dtnd ..."
	
	# startup the safety-wrapper for the daemon
	/usr/sbin/dtnd-safety-wrapper.sh &
	
	# store the pid of the process in uci states
	/sbin/uci -P/var/state -q set ibrdtn.safetypid=`echo $!`
	
	/bin/echo " done"
}

stop() { 
	# check if the daemon is disabled
	if [ "`/sbin/uci -P/var/state -q get ibrdtn.disable`" == "1" ]; then
		/bin/echo "dtnd is disabled"
		return
	fi
	
	/bin/echo -n "stopping dtnd ..."
	
	# set state to None, this indicates a clear shutdown to the safety-wrapper.
	/sbin/uci -P/var/state -q set ibrdtn.state=None
	
	# stop the safety-wrapper
	if [ -n "`/sbin/uci -P/var/state -q get ibrdtn.safetypid`" ]; then
		/usr/bin/kill `/sbin/uci -P/var/state -q get ibrdtn.safetypid` 2> /dev/null >/dev/null
	fi
	
	# finally kill really all safety-wrapper!
	/bin/sleep 2
	/usr/bin/killall -9 dtnd-safety-wrapper.sh
	
	# send a kill signal to the daemon
	/usr/bin/killall dtnd 2> /dev/null >/dev/null
	
	# wait for some time
	TIMEOUT=0;
	
	# check if the daemon is running
	while [ -n "`ps | grep dtnd | grep -v grep`" ]; do
		# check if the daemon is still running
		if [ $TIMEOUT -ge 10 ]; then
			/bin/echo " killing"
			# kill all processes of dtnd
			/usr/bin/killall -9 dtnd 2> /dev/null >/dev/null
			return
		fi
		
		# increment timeout
		TIMEOUT=`expr $TIMEOUT + 1`
		
		echo -n "."
		
		# wait some time
		/bin/sleep 1
	done
	
	echo " done"
}