#!/bin/bash
#
# Init file for the TrouSerS TCG Core Services daemon
#
# chkconfig: - 90 10
# description: TrouSerS server daemon
#
# processname: tcsd
# config: /etc/tcsd.conf
# pidfile: /var/run/tcsd.pid
#
# Return values according to LSB for all commands but status:
# 0 - success
# 1 - generic or unspecified error
# 2 - invalid or excess argument(s)
# 3 - unimplemented feature (e.g. "reload")
# 4 - insufficient privilege
# 5 - program is not installed
# 6 - program is not configured
# 7 - program is not running
#

prog="tcsd"

# source function library
. /etc/rc.d/init.d/functions

# Allow anyone to run status
if [ "$1" = "status" ] ; then
	status $prog
	RETVAL=$?
	exit $RETVAL
fi

# Check that we are root ... so non-root users stop here
test $EUID = 0  ||  exit 4

# pull in sysconfig settings
test -f /etc/sysconfig/tcsd  && . /etc/sysconfig/tcsd

RETVAL=0

# Some variables to make the below more readable
TCSD=/usr/sbin/tcsd
PID_FILE=/var/run/tcsd.pid
INSMOD=/sbin/insmod
LSMOD=/sbin/lsmod
GREP=/bin/grep

load_drivers()
{
	for d in `echo /lib/modules/$(uname -r)/kernel/drivers/char/tpm/tpm_*`; do
		$INSMOD $d
		if test $? -eq 0; then
			break;
		fi
	done
}

check_drivers()
{
	$LSMOD | $GREP tpm_
}

start()
{
	test -x $TCSD || exit 5
	test -f /etc/tcsd.conf || exit 6
	check_drivers || load_drivers || failure
	echo -n $"Starting $prog: "
	$TCSD $OPTIONS && success || failure
	RETVAL=$?
	[ "$RETVAL" = 0 ] && touch /var/lock/subsys/tcsd
	echo
}

stop()
{
	echo -n $"Stopping $prog: "
	killproc $prog
	RETVAL=$?
	[ "$RETVAL" = 0 ] && rm -f /var/lock/subsys/tcsd
	echo
}

case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	restart)
		test -f /etc/tcsd.conf  || exit 6
		stop
		start
		;;
	reload|force-reload)
		restart
		;;
	condrestart|try-restart)
		if [ -f /var/lock/subsys/tcsd ] ; then
			restart
		fi
		;;
	*)
		echo $"Usage: $0 {start|stop|restart|reload|force-reload|condrestart|try-restart|status}"
		RETVAL=3
esac
exit $RETVAL
