#!/bin/bash
#
# pcscd        Starts the pcscd Daemon
#
#
# chkconfig: 2345 12 88
# description: PC/SC Smart Card Daemon
#
# processname: pcscd
# pidfile: /var/run/pcscd/pcscd.pid

### BEGIN INIT INFO
# Provides: pcscd
# Required-Start: $local_fs $remote_fs $syslog haldaemon
# Required-Stop: $local_fs $remote_fs $syslog haldaemon
# Should-Start: openct
# Should-Stop: openct
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Daemon to access a smart card using PC/SC
# Description: The PC/SC smart card daemon is a resource manager for the
#              PC/SC lite and Musclecard frameworks.  It coordinates
#              communications with smart card readers, smart cards, and
#              cryptographic tokens that are connected to the system.
### END INIT INFO

# Do not load RH compatibility interface.
WITHOUT_RC_COMPAT=1

. /etc/init.d/functions
PIDFILE=/var/run/pcscd/pcscd.pid
LOCKFILE=/var/lock/subsys/pcscd

# Set defaults
LOGGING="yes"

# Get service config - may override defaults
[ -f /etc/sysconfig/pcscd ] && . /etc/sysconfig/pcscd

if [ "$LOGGING" == "yes" ]; then
	LOGOPT="-d"
else
	LOGOPT=""
fi

# I can't read process pid from /var/run/pcscd/pcscd.pid
# Remove /var/run/pcscd/pcscd.comm
# if pcscd is not running to clear this message.
cleanup()
{
	if pid="`pidof pkcs11_eventmgr >&/dev/null`"; then
		if [ -f "$PIDFILE" -a "$pid" = "$(cat "$PIDFILE")" ]; then
			return
		fi
	fi
	rm -f /var/run/pcscd/pcscd.comm
}

RETVAL=0
start() {
	cleanup
	start_daemon $PCSCD_RUN_NICE_LEVEL --pidfile "$PIDFILE" --lockfile "$LOCKFILE" --expect-user root -- pcscd $LOGOPT
	RETVAL=$?
	return $RETVAL
}

stop() {
	stop_daemon --pidfile "$PIDFILE" --lockfile "$LOCKFILE" --expect-user root -- pcscd
	RETVAL=$?
	return $RETVAL
}

restart() {
	stop
	start
}

case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	status)
		status --expect-user root -- pcscd
		RETVAL=$?
		;;
	condstop)
		if [ -e "$LOCKFILE" ]; then
			stop
		fi
		;;
	condrestart)
		if [ -e "$LOCKFILE" ]; then
			restart
		fi
		;;
	condreload)
		if [ -e "$LOCKFILE" ]; then
			restart
		fi
		;;
	restart|reload)
		restart
		;;
	*)
		msg_usage "${0##*/} {start|stop|reload|restart|condstop|condrestart|condreload|status}"
		RETVAL=1
esac

exit $RETVAL
