#!/bin/bash
### BEGIN INIT INFO
# Provides:          trousers
# Required-Start:    $local_fs $network
# Required-Stop:
# Should-Start:      udev
# Should-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:      S 0 1 6
# Short-Description: Start or stop TrouSerS tcsd daemon.
# Description:
### END INIT INFO

set -e

DESC="TrouSerS TCS daemon"
NAME=tcsd
DAEMON=/usr/sbin/tcsd
DEFAULTFILE=/etc/default/trousers

[ -x $DAEMON ] || exit 0

[ -f $DEFAULTFILE ] && . $DEFAULTFILE

. /lib/lsb/init-functions
. /etc/default/rcS

case "$TROUSERS_ENABLE" in
  [Nn]*)
    log_warning_msg "To enable $NAME, edit $DEFAULTFILE and set TROUSERS_ENABLE=yes"
    exit 0
    ;;
esac

load_modules() {
	if [ -n "${TPM_MODULES}" ]; then
	    for d in ${TPM_MODULES}; do
	        if echo `/sbin/lsmod` | grep -q -w "$d"; then
		    [ "$VERBOSE" != no ] && log_success_msg "Module already loaded: $d"
		    continue
		else
		    if modprobe -q $d $MODULE_OPTS 2>/dev/null; then
		        [ "$VERBOSE" != no ] && log_success_msg "Loaded module: $d"
			continue
		    else
		        if [ "$VERBOSE" != no ]; then
		            log_warning_msg "Unable to load module: $d"
			    continue
			fi
		    fi
		fi
	    done
	fi
}

check_modules() {
	if [ ! -c /dev/tpm ] && [ ! -c /dev/tpm0 ]; then
	    log_warning_msg "Not starting $DESC ($NAME); no TPM device found."
	    exit 0
	fi
}

tcsd_start() {
	load_modules
	check_modules
	log_daemon_msg "Starting $DESC" "$NAME"
	start-stop-daemon --start --quiet --chuid tpm --exec $DAEMON
	log_end_msg $?
}

tcsd_stop() {
	log_daemon_msg "Stopping $DESC" "$NAME"
	start-stop-daemon --stop --quiet --oknodo --exec $DAEMON --user tpm
	log_end_msg $?
}

case "$1" in
  start)
    tcsd_start
    ;;
  stop)
    tcsd_stop
    ;;
  restart|reload|force-reload)
    tcsd_stop
    tcsd_start
    ;;
  *)
    log_success_msg "Usage: $0 {start|stop|restart|reload|force-reload}"
    exit 1
  ;;
esac

exit 0
