#!/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): Ericsson AB
#

source "/etc/opensaf/script.conf"

CMD=$1

NAME=smfnd
TOOL=$SMFNDTOOL
SERVICE=`echo $NAME | tr '[:lower:]' '[:upper:]'`

BIN=${LIBPATH}/opensaf_$NAME
COMPNAMEFILE=${LOCALSTATEDIR}/$NAME_comp_name
LOGFILE=${NCS_STDOUTS_PATH}/opensaf_$NAME.log
PIDFILE=${PIDPATH}/opensaf_$NAME.pid
CONFFILE=${SYSCONFDIR}/$NAME.conf

test -f $CONFFILE && source $CONFFILE
test -f $PIDFILE && PID=`cat $PIDFILE`

start()
{
    test -p $NIDFIFO || exit 1

    if [ ! -x $BIN ]; then
        logger -s -t $0 "ERROR: File $BIN does not exist or is not executable"
        echo "$NID_MAGIC:$SERVICE:$DAEMON_NOT_FND" > $NIDFIFO
        exit 1
    fi

    test -f $PIDFILE && kill -KILL $PID

    export ${SERVICE}_COMP_NAME_FILE=$COMPNAMEFILE

    $TOOL $BIN >> $LOGFILE 2>&1 &
   
    if [ $? -ne 0 ]; then
        logger -s -t $0 "ERROR: Cannot start $BIN."
        echo "$NID_MAGIC:$SERVICE:$DAEMON_START_FAILED" > $NIDFIFO
        exit 1
    fi
}

instantiate()
{
    echo $SA_AMF_COMPONENT_NAME > $COMPNAMEFILE

    # If the process exist it has been started earlier by NID, send signal to it.
    # If the process does not exist, AMF wants it (re)started.
    if test -f $PIDFILE; then
        kill -USR1 $PID
    else
        $TOOL $BIN >> $LOGFILE 2>&1 &
    fi
}

stop()
{
    # Allow tools to dump results to file system before exit
    if test -f $PIDFILE; then
	if [ "$TOOL" == "" ]; then
	    kill -KILL $PID
	else
	    kill -TERM $PID
	fi
    fi

    rm -f $COMPNAMEFILE
    rm -f $PIDFILE
}

case "$CMD" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    instantiate)
        instantiate
        ;;
    cleanup)
        stop
        ;;
    *)
        echo "Usage: $0 {start|stop|instantiate|cleanup}"
        exit 1
esac

exit 0

