#!/bin/sh
# /etc/init.d/ledcio
#
# Written by Russell Cumber<Russell.Cumber@daktronics.com>

set -e

DAEMON=/usr/local/sbin/ledcio
NAME=ledcio
PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin

DAEMON_OPTS=""
#DAEMON_OPTS="--doorthresholdmsec 1000" #1000ms is the default in ledcio. use this to override.

test -x $DAEMON || exit 0

case "$1" in
  start)
    echo -n "Starting app: $NAME  "
    [ -d /var/run/ledcio ] || mkdir -p /var/run/ledcio
    modprobe spiccd
    start-stop-daemon --start --background -m --pidfile /var/run/ledcio/ledcio.pid --exec $DAEMON -- $DAEMON_OPTS
    echo "."
    ;;
  stop)
    echo -n "Stopping app: $NAME  "
    start-stop-daemon --stop --pidfile /var/run/ledcio/ledcio.pid --oknodo --exec $DAEMON
    rm -f /var/run/ledcio/ledcio.pid
    echo "."
    ;;
  restart)
    echo -n "Restarting app: $NAME  "
	
	set +e #enable error checking incase process wasn't running
    start-stop-daemon --stop --pidfile /var/run/ledcio/ledcio.pid  -q --exec $DAEMON
	if [ "$?" = "1" ]; then
		sleep 1 #if process wasn't running give it one second to see if it comes up (incase this script gets called twice really fast) and try again
		start-stop-daemon --stop --pidfile /var/run/ledcio/ledcio.pid  --oknodo --exec $DAEMON
	fi
	set -e
	
    rm -f /var/run/ledcio/ledcio.pid
	if [ $2 ]; then
		start-stop-daemon --start --background -m --pidfile /var/run/ledcio/ledcio.pid --exec $DAEMON  -- -hbrate $2
	else
		start-stop-daemon --start --background -m --pidfile /var/run/ledcio/ledcio.pid --exec $DAEMON  -- $DAEMON_OPTS
	fi
    echo "."
    ;;
  reload|force-reload)
    echo "Reloading $NAME configuration files  "
    start-stop-daemon --stop --pidfile /var/run/ledcio/ledcio.pid --signal 1 --exec $DAEMON
    echo "."
    ;;
  *)
    echo "Usage: /etc/init.d/$NAME {start|stop|restart|reload}"
    exit 1
    ;;
esac

exit 0
