#!/bin/sh
#
# start/stop p910nd printserver daemon.

### BEGIN INIT INFO
# Provides:          p910nd
# Required-Start:    $network $syslog
# Required-Stop:     $network $syslog
# Default-Start:     3 4 5
# Default-Stop:      0 1 6
# Short-Description: p910nd a non-spooling printserver
### END INIT INFO

if [ -f /etc/default/p910nd ]; then
  . /etc/default/p910nd
elif [ -f /etc/p910nd.conf ]; then
  . /etc/p910nd.conf
fi

# p910 uses a different process name for each port
NAME=p910${P910ND_PORT}d
PIDFILE=/var/run/$NAME.pid
SCRIPTNAME=/etc/init.d/p910nd
DESC="p910nd printserver"
DAEMON=/usr/sbin/p910nd
DAEMON_OPTS="-f $P910ND_DEV $P910ND_OPTS $P910ND_PORT"

test -x $DAEMON || exit 0

. /lib/lsb/init-functions

# --- determine current status and correct if necessary the pidfile
#     return state
isrunning()
{
        procpid=`pidof $NAME`
        if [ -n "$procpid" ] ; then     # process is running
           pid=xx
           [ -r $PIDFILE ] &&  pid=`cat $PIDFILE`
           [ "$procpid" != "$pid" ] &&  echo "$procpid" >$PIDFILE
           echo $procpid
           return 1
        else
           [ -r $PIDFILE ] && rm -f $PIDFILE
        fi
        echo 0
	return 0
}


case "$1" in
  start)
	log_daemon_msg "Starting $DESC" $NAME
        pid=`isrunning`
        if [ $pid -ne 0 ] ; then
		log_begin_msg " is already started (pid=$pid)"
		log_end_msg 0 
	else
		start-stop-daemon --start --quiet --exec $DAEMON -- $DAEMON_OPTS
		log_end_msg $?
	fi
    ;;
  stop)
	log_daemon_msg "Stopping $DESC" $NAME
        pid=`isrunning`
        if [ $pid -eq 0 ] ; then
		log_begin_msg " is already stopped"
		log_end_msg 0 
        else
  		start-stop-daemon --quiet --stop --oknodo --pidfile $PIDFILE
		log_end_msg $?
	fi
	[ -r $PIDFILE ] && rm -f $PIDFILE
	;;
  reload|restart|force-reload)
	$0 stop
	$0 start
	;;
  status)
	log_action_begin_msg "Status $DESC" $NAME
        pid=`isrunning`
        [ $pid -ne 0 ] && log_action_msg " is running (pid=$pid)"
        [ $pid -eq 0 ] && log_action_msg " is not running"
	;;
  *)
	echo "Usage: $SCRIPTNAME {start|stop|restart|reload|force-reload|status}" >&2
	exit 1
	;;
esac

exit 0
