#! /bin/sh
#
# skeleton	example file to build /etc/init.d/ scripts.
#		This file should be used to construct scripts for /etc/init.d.
#
#		Written by Miquel van Smoorenburg <miquels@cistron.nl>.
#		Modified for Debian GNU/Linux
#		by Ian Murdock <imurdock@gnu.ai.mit.edu>.
#
# Version:	@(#)skeleton  1.8  03-Mar-1998  miquels@cistron.nl
#
# This file was automatically customized by dh-make on Sun, 27 Aug 2000 02:30:47 +0900

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/sbin/pdnsd
NAME=pdnsd
DESC="domain name service"

CACHE=/var/cache/pdnsd/pdnsd.cache

test -f $DAEMON || exit 0

gen_cache () {
	if [ -f $CACHE ]; then
		CACHE_SIZE=`LANG=C ls -l $CACHE | awk '{ print $5; }'`
		if expr $CACHE_SIZE '<' 4 > /dev/null; then
			echo "Disk cache file is broken, regenerate it."
			dd if=/dev/zero of=$CACHE bs=1 count=4 > /dev/null
			chown pdnsd.proxy $CACHE
		fi
	else
		echo "Disk cache file is broken, regenerate it."
		mkdir -p /var/cache/pdnsd
		dd if=/dev/zero of=$CACHE bs=1 count=4 > /dev/null
		chown -R pdnsd.proxy /var/cache/pdnsd
	fi	
}

set -e

test -f /etc/default/pdnsd || exit 0
. /etc/default/pdnsd

case "$1" in
  start)
    gen_cache
	echo -n "Starting $DESC: "
	start-stop-daemon --start --oknodo --quiet --pidfile /var/run/$NAME.pid --name pdnsd --exec $DAEMON -- --daemon -p /var/run/$NAME.pid $START_OPTIONS || echo -n " already running. "
	echo "$NAME."
	;;
  stop)
	echo -n "Stopping $DESC: "
	PID=`cat /var/run/$NAME.pid`
	start-stop-daemon --stop --oknodo --quiet --pidfile /var/run/$NAME.pid --name pdnsd
	if test -n "$PID" && kill -0 $PID 2>/dev/null
        then
		echo -n "Waiting ."
		cnt=0
		while kill -0 $PID 2>/dev/null
		  do
		  cnt=`expr $cnt + 1`
		  if [ $cnt -gt 60 ]
			  then
			  echo -n " Failed.. "
			  break
		  fi
		  sleep 2
		  echo -n "."
		done
		echo "done."
	else
		echo "$NAME."
	fi
	;;
  restart|force-reload)
	echo "Restarting $DESC..."
	$0 stop
	sleep 2
	$0 start
	;;
  *)
	N=/etc/init.d/$NAME
	# echo "Usage: $N {start|stop|restart|reload|force-reload}" >&2
	echo "Usage: $N {start|stop|restart|force-reload}" >&2
	exit 1
	;;
esac

exit 0
