#!/bin/sh
### BEGIN INIT INFO
# Provides:          FA_CanManager
# 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 CanManager.
# Short-Description:	Runs CanManager.
### 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 CanManager binary.


. /lib/lsb/init-functions

PATH=/sbin:/bin:/usr/sbin:/usr/bin
CANMANAGER_KEEPALIVE_SCRIPT=KA_CanManager
CANMANAGER_BINARY=/6100/bin/CanManager
SCRIPTNAME=FA_CanManager

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

stop()
{
    local ISRUNNING=`ps ax | grep -v grep | grep $CANMANAGER_BINARY`
    # If the application is running, kill it.
    if [[ -n $ISRUNNING ]]; then
	# Kill both the keepalive script and the binary.
	killall $CANMANAGER_KEEPALIVE_SCRIPT
	killall $CANMANAGER_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 $CANMANAGER_BINARY`

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

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


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