#! /bin/sh
#
# /etc/init.d/openct
#
### BEGIN INIT INFO
# Provides:          openct
# Required-Start:    $remote_fs
# Required-Stop:     $remote_fs
# Should-Start:      $syslog
# Should-Stop:       $syslog
# Default-Start:     2 3 5
# Default-Stop:
# Short-Description: Smart card terminal framework
# Description:       Runs drivers for smart card readers
### END INIT INFO

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/sbin/openct-control
NAME=OpenCT
DESC="smart card terminal framework"

# Shell functions sourced from /etc/rc.status:
#      rc_check         check and set local and overall rc status
#      rc_status        check and set local and overall rc status
#      rc_status -v     ditto but be verbose in local rc status
#      rc_status -v -r  ditto and clear the local rc status
#      rc_failed        set local and overall rc status to failed
#      rc_reset         clear local rc status (overall remains)
#      rc_exit          exit appropriate to overall rc status
. /etc/rc.status

rc_reset

# Return values acc. to LSB for all commands but status:
# 0 - success
# 1 - misc error
# 2 - invalid or excess args
# 3 - unimplemented feature (e.g. reload)
# 4 - insufficient privilege
# 5 - program not installed
# 6 - program not configured
#
# Note that starting an already running service, stopping
# or restarting a not-running service as well as the restart
# with force-reload (in case signalling is not supported) are
# considered a success.

test -x $DAEMON || exit 5

# create the directory for our status and socket files,
# if it does not exist.
if ! test -e "/var/run/openct"
then
	mkdir "/var/run/openct"

	# maybe you also want to set owner ship and permissions here.
	# this example would assign the directory to a group "scard"
	# and set permissions so only users in that group can access
	# smart card readers via openct.
	chown daemon:daemon "/var/run/openct"
	chmod 0755 "/var/run/openct"
fi

case "$1" in
  start)
	echo -n "Starting $DESC: $NAME"
	$DAEMON init
	rc_status -v
	;;
  stop)
	echo -n "Stopping $DESC: $NAME "
	if test -f /var/run/openct/status ; then
	    $DAEMON shutdown
	fi
	rc_status -v
	;;
  reload)
  	;;
  restart|force-reload)
	#
	#	If the "reload" option is implemented, move the "force-reload"
	#	option to the "reload" entry above. If not, "force-reload" is
	#	just the same as "restart".
	#
	echo -n "Restarting $DESC: $NAME "
	if test -f /var/run/openct/status ; then
	    $DAEMON shutdown
	fi
	sleep 0.1
	$DAEMON init
	rc_status -v
	;;
  try-restart)
	$0 status >/dev/null &&  $0 restart
	rc_status
	;;
  status)
  	echo -n "Checking for $DESC: $NAME"
	if openct-tool list >/dev/null 2>&1; then
		rc_failed 0
	else
		rc_failed 3
	fi
	rc_status -v
	;;
  *)
	echo "Usage: $0 {start|stop|status|try-restart|restart|force-reload|reload}" >&2
	exit 1
	;;
esac

exit 0
