#! /bin/sh
#
# rng-tools	initscript for the rng-tools package
#		Copr. 2003 by Henrique de Moraes Holschuh <hmh@debian.org>
#		Copr. 2002 by Viral Shah <viral@debian.org>
#
# $Id: rng-tools.init,v 1.6 2004/03/09 20:30:13 hmh Exp $

PATH=/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/sbin/rngd
NAME=rngd
DESC="Hardware RNG entropy gatherer daemon"
PIDFILE=/var/run/rngd.pid

HRNGDEVICE=/dev/hwrandom
RNGDOPTIONS=
[ -r /etc/default/rng-tools ] && . /etc/default/rng-tools

test -f ${DAEMON} || exit 0

set -e

finddevice () {
	for i in ${HRNGDEVICE} /dev/hwrandom /dev/hw_random /dev/misc/hw_random ; do
		[ -c "$i" ] && {
			HRNGDEVICE="$i"
			return 0
		}
	done

	echo "(Hardware RNG device inode not found)"
	echo "$0: Cannot find a hardware RNG device to use." >&2
	exit 1
}

START="--start --quiet --pidfile ${PIDFILE} --exec ${DAEMON}"
case "$1" in
  start)
	echo -n "Starting $DESC: "
	finddevice
	START="${START} -- -r ${HRNGDEVICE} ${RNGDOPTIONS}"
	if start-stop-daemon ${START} >/dev/null 2>&1 ; then
		echo "${NAME}."
	else
		if start-stop-daemon --test ${START} >/dev/null 2>&1; then
			echo "(failed)."
			exit 1
		else
			echo "${DAEMON} already running."
			exit 0
		fi
	fi
	;;
  stop)
	echo -n "Stopping $DESC: "
	if start-stop-daemon --stop --quiet --pidfile ${PIDFILE} \
		--startas ${DAEMON} >/dev/null 2>&1 ; then
			echo "${NAME}."
	else
		echo "(failed)."
	fi
	;;
  restart|force-reload)
	$0 stop && {
	  echo -n "Waiting for complete shutdown..."
	  i=5
	  while [ $i -gt 0 ] ; do
	  	if start-stop-daemon --start --test \
		   --pidfile ${PIDFILE} \
		   --exec ${DAEMON} >/dev/null 2>&1 ; then
		       break
		fi
		sleep 2s
		i=$(($i - 1))
		echo -n "."
	  done
	  [ $i -eq 0 ] && {
		echo
		echo "fatal: incomplete shutdown detected, aborting."
		exit 1
	  }
	  echo
	}
	exec $0 start	    
	;;
  *)
	echo "Usage: $0 {start|stop|restart|force-reload}" 1>&2
	exit 1
	;;
esac

exit 0
