#!/bin/sh
### BEGIN INIT INFO
# Provides:          FA_CameraManager_Serial
# 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 CameraManager_Serial.
# Short-Description: Runs CameraManager_Serial.
### END INIT INFO


# Author: John Schluechtermann <jschluechtermann@forceamerica.com>
# Project: P1131 - 6100 Spreader Control
# Created: 06/21/2018

PATH=/sbin:/bin:/usr/sbin:/usr/bin
KEEPALIVE_SCRIPT=KA_CameraManager_Serial
BINARY=/6100/bin/CameraManager_Serial
SCRIPTNAME=FA_CameraManager_Serial

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

stop()
{
    local ISRUNNING=`ps | grep -v grep | grep $BINARY`
    # If the application is running, kill it.
    if [[ -n $ISRUNNING ]]; then
	# Kill both the keepalive script and the binary.
	ps | grep -v grep | grep "$KEEPALIVE_SCRIPT" | awk '{print $1}' | xargs kill
	ps | grep -v grep | grep "$BINARY" | awk '{print $1}' | xargs kill 
    else
	echo "$BINARY is not running."
    fi
}

restart()
{
    local ISRUNNING=`ps | grep -v grep | grep $BINARY`
    # If the application is running, kill it.
    if [[ -n $ISRUNNING ]]; then
	# Kill both the keepalive script and the binary.
	ps | grep -v grep | grep "$KEEPALIVE_SCRIPT" | awk '{print $1}' | xargs kill
	ps | grep -v grep | grep "$BINARY" | awk '{print $1}' | xargs kill 
    else
	echo "$BINARY is not running."
    fi

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


case "$1" in
    start)
    echo "Starting CameraManager_Serial"
	start
	;;
    stop)
    echo "Stopping CameraManager_Serial"
	stop
	;;
    restart)
    echo "Restarting CameraManager_Serial"
	restart
	;;
    *)
	echo "Usage: $SCRIPTNAME {start|stop|restart}" >&2
	exit 3
	;;
esac
