#! /bin/sh
#
# /etc/init.d/pcscd
# Start/Stop/Restart PCSC Lite resource manager daemon
#
# Carlos Prados Bocos <cprados@debian.org>
# modifications by Ludovic Rousseau <rousseau@debian.org>

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
NAME=pcscd
DAEMON=/usr/sbin/$NAME
DESC="PCSC Lite resource manager"

PIDFILE=/var/run/$NAME.pid
SCRIPTNAME=/etc/init.d/$NAME

# Gracefully exit if the package has been removed (but not purged).
test -x $DAEMON || exit 0

if [ -f /lib/lsb/init-functions ]; then
	. /lib/lsb/init-functions
else
	log_success_msg() { echo "$@"; }
	log_warning_msg() { echo "$@"; }
	log_failure_msg() { echo "$@"; }
fi

set -e

case "$1" in
  start)
	echo -n "Starting $DESC: $NAME"
	# if the daemon is already running we REstart it
	if [ -f $PIDFILE ]; then
	  echo " already running."
	  $0 restart
	else
	  start-stop-daemon --start --quiet --pidfile $PIDFILE \
	    --exec $DAEMON -- --error
	  echo "."
	fi
	;;

  stop)
	echo -n "Stopping $DESC: $NAME"
	start-stop-daemon --stop --quiet --oknodo --pidfile $PIDFILE \
	  --name $NAME
	echo "."
	;;
	
  restart|force-reload)
	$0 stop
	echo -n "Starting $DESC: $NAME"
	sleep 2
	start-stop-daemon --start --quiet --pidfile $PIDFILE \
		--exec $DAEMON -- --error
	echo "."
	;;
	
  restart-if-running)
    echo -n "Restarting $DESC if it is running: $NAME"
	if $0 status &> /dev/null
	then
		echo "."
		$0 restart
	else
		echo " (not running)."
	fi
	;; 

  status)
	if [ -e $PIDFILE ] ; then
		if ps -p $(cat $PIDFILE) &> /dev/null ; then
			echo "running"
			exit 0
		else
			echo "not running and $PIDFILE exists"
			exit 1
		fi
	else
		echo "not running"
		exit 3
	fi
	;;

  *)
	echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload|restart-if-running|status}" >&2
	exit 1
	;;
esac

exit 0

