#!/bin/bash
#
#      -*- OpenSAF  -*-
#
# (C) Copyright 2008 The OpenSAF Foundation
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. This file and program are licensed
# under the GNU Lesser General Public License Version 2.1, February 1999.
# The complete license can be accessed from the following location:
# http://opensource.org/licenses/lgpl-license.php
# See the Copying file included with the OpenSAF distribution for full
# licensing terms.
#
# Author(s): Emerson Network Power
#

source "/etc/opensaf/script.conf"

XTERM=""

#XTERM="xterm -T OpenSAF-EDS -e "

#XTERM="xterm -T OpenSAF-EDS -e /usr/bin/gdb "
# Set this if debugging required.

DAEMON=ncs_eds
PIDFILE=eds.pid
COMPNAMEFILE="$LOCALSTATEDIR/ncs_eds_comp_name"
NID_SVC_NAME=EDSV

echo "Executing EDSv init-script..."
echo "NCS_STDOUTS_PATH=$NCS_STDOUTS_PATH"

#Function to start/spawn a service.
start()
{

    echo "Starting EDSv..."
    #Check if daemon is installed.
    if [ ! -x "$LIBPATH/$DAEMON" ]; then
       echo -n -e "Unable to find daemon: $LIBPATH/$DAEMON     \n"
       echo "$NID_MAGIC:$NID_SVC_NAME:$DAEMON_NOT_FND" > $NIDFIFO
       exit 1
    fi
    killall ncs_eds
    rm -f $PIDPATH/$PIDFILE
    $XTERM "$LIBPATH/ncs_eds" "$*" >"$NCS_STDOUTS_PATH/ncs_eds.log" 2>&1 &
    echo "Starting $DESC: $LIBPATH/$DAEMON";

    if [ $? -ne 0 ] ; then
	echo -n -e "Failed to start $DAEMON.    \n"
	echo "$NID_MAGIC:$NID_SVC_NAME:$DAEMON_START_FAILED" > "$NIDFIFO"
	exit 0
     else
         echo "Started $DESC: $LIBPATH/$DAEMON"
     fi

} # End start()


case "$1" in
   start)
   shift
   start $*
      ;;
   "")
   # AMF would call with no arguments
	echo $SA_AMF_COMPONENT_NAME

	#remove the existing $COMPNAMEFILE 
	rm -f $COMPNAMEFILE

	#echo the component name into a temporary text file
	echo $SA_AMF_COMPONENT_NAME > $COMPNAMEFILE

	# check for the PID availability
	if test -f "$PIDPATH/$PIDFILE"
	then
	   l_pid=`cat "$PIDPATH/$PIDFILE"`
	fi
      
	if [ "$l_pid" ]
   	then
	   echo "Sending the SIGUSR1 to ncs_eds ..."
	   `kill -USR1 $l_pid`
	else
            echo "Re-Starting EDSv"
		start ;
		sleep 10s
		#Check if the process is running and send a signal
		if test -f "$PIDPATH/$PIDFILE"
		then
			l_pid=`cat "$PIDPATH/$PIDFILE"`
		fi

		echo $l_pid
		if [ "$l_pid" ]
		then `kill -USR1 $l_pid`
        	fi
	fi
     exit 0 # Report to AMF.
     ;;
esac;

