#!/bin/sh
### BEGIN INIT INFO
# Provides:          FA_SerialManager
# Required-Start:    $local_fs $remote_fs
# Required-Stop:     $local_fs $remote_fs
# Default-Start:     S 2 3 4 5
# Default-Stop:      0 1 6
# Description:       This script launches SerialManager.
# Short-Description:	Runs SerialManager.
### END INIT INFO


# Author: Andrew Dorney <adorney@forceamerica.com>
# Project: P1131 - 6100 Spreader Control
# Created: 05/11/2009
# Modified: 05/25/2011 by Andrew Dorney (P1131)
#           - Fixed issue where passing "restart" to the script wouldn't re-launch the SerialManager binary.


. /lib/lsb/init-functions

PATH=/sbin:/bin:/usr/sbin:/usr/bin
SERIALMANAGER_KEEPALIVE_SCRIPT=KA_SerialManager
SERIALMANAGER_BINARY=/6100/bin/SerialManager
SCRIPTNAME=FA_SerialManager

start()
{
    # If persistd isn't executable, quit.
    if [[ ! -x "$SERIALMANAGER_BINARY" ]]; then
	log_action_end_msg 1
	echo "$SERIALMANAGER_BINARY is not executable."
	return 1
    else
        # Otherwise, launch the keepalive script which runs SerialManager for us.
	/6100/rc/$SERIALMANAGER_KEEPALIVE_SCRIPT $SERIALMANAGER_BINARY &
        log_action_end_msg 0
    fi
}

stop()
{
    local ISRUNNING=`ps ax | grep -v grep | grep $SERIALMANAGER_BINARY`
    # If the application is running, kill it.
    if [[ -n $ISRUNNING ]]; then
	# Kill both the keepalive script and the binary.
	killall $SERIALMANAGER_KEEPALIVE_SCRIPT
	killall $SERIALMANAGER_BINARY
        log_action_end_msg 0
    else
        log_action_end_msg 1
    fi
}

restart()
{
    # If the application is running, kill it.
    local ISRUNNING=`ps ax | grep -v grep | grep $SERIALMANAGER_BINARY`

    if [[ -n $ISRUNNING ]]; then
	# Kill both the keepalive script and the binary.
	killall $SERIALMANAGER_KEEPALIVE_SCRIPT
	killall $SERIALMANAGER_BINARY
    else
	echo "$SERIALMANAGER_BINARY is not running"
    fi

    # Then, restart it.
    # If the application isn't executable, quit.
    if [[ ! -x "$SERIALMANAGER_BINARY" ]]; then
	echo "$SERIALMANAGER_BINARY is not executable."
	log_action_end_msg 1
    else
        # Otherwise, start the keepalive script, which launches SerialManager for us.
	/6100/rc/$SERIALMANAGER_KEEPALIVE_SCRIPT $SERIALMANAGER_BINARY &
        log_action_end_msg 0
    fi
}


case "$1" in
    start)
	log_action_msg "Starting SerialManager"
	start
	;;
    stop)
	log_action_msg "Stopping SerialManager"
	stop
	;;
    restart)
	log_action_msg "Restarting SerialManager"
	restart
	;;
    *)
	# echo "Usage: $SCRIPTNAME {start|stop|restart|reload|force-reload}" >&2
	echo "Usage: $SCRIPTNAME {start|stop|restart}" >&2
	exit 3
	;;
esac
