#!/bin/sh
NAME=pcscd
PIDFILE=/var/run/pcscd/pcscd.pid
PCSCD=/usr/local/sbin/pcscd
OPTS=""

. /etc/init.d/tc-functions

getpid() {
	ps -eo pid,args | grep -E "[0-9]+ $PCSCD" | awk '{print "",$1;}' | tr -d '\n'
}

success() {
	echo "OK";
	return 0
}

failure() {
	echo FAILED
	return 1
}

start() {
	echo -n Starting ${NAME}...
	if [ -x $PCSCD ] && [ ! -n "$(getpid)" ]; then
		mkdir -p $(dirname $PIDFILE) 2>/dev/null
		$PCSCD $OPTS && success || failure
	else
		failure
	fi 
}

stop() {
	echo -n Stopping ${NAME}...
	if [ -e $PIDFILE ] || [ -n "$(getpid)" ]; then
		kill $(cat $PIDFILE 2>/dev/null)
		[ $? -ne 0 ] && kill -9 $(getpid)
		rm -f $PIDFILE 2>/dev/null
		success
	else
		failure
	fi 
}

status() {
	PIDS=$(getpid)
	[ -z "$PIDS" ] && { echo "$NAME is stopped"; return 1; } || echo "$NAME (pid$PIDS) is running"
}

case $1 in
  start) start ;;
  stop) stop ;;
  restart) stop ; start ;;
  status) status ;;
  *) echo "Usage: $0 [start|stop|restart|status]" ;;
esac
