#!/bin/sh
#
# Appcore:   Appcore daemon
#
# chkconfig: - 85 15
# description:  This is an Appcore daemon.
#
# processname: Appcore
#
### BEGIN INIT INFO
# Provides: Appcore
# Required-Start: $remote_fs $syslog
# Required-Stop:  $remote_fs $syslog
# Default-Start:  3 5
# Default-Stop:   0 1 2 6
# Description:    Appcore
### END INIT INFO

# Source function library.
#. /etc/rc.d/init.d/functions

INSTALL_PATH=APPCORE_INSTALL_PATH
ERL_PATH=$INSTALL_PATH/erlang
APPCORE_VER=`ls $ERL_PATH/lib | grep appcore`
APPCORE_LIB_PATH=$INSTALL_PATH/appcore
HOME=$ERL_PATH/lib/$APPCORE_VER/ebin
HEART_COMMAND="service Appcore restart"

# so we can rearrange this easily

RETVAL=0
ERL_RELEASE_PARAMS="-heart -name erlac@127.0.0.1 -pa `find $ERL_PATH/lib | grep -e "ebin$"` -detached -noinput -s appcore"
ERL_DEBUG_PARAMS="-heart -name erlac@127.0.0.1 -pa `find $ERL_PATH/lib | grep -e "ebin$"` -boot start_sasl"

start()
{
	cd $ERL_PATH/lib/$APPCORE_VER/ebin
	echo $"Starting Appcore daemon..."
	$ERL_PATH/bin/erl $ERL_PARAMS

	RETVAL=$?
}

stop()
{
	echo $"Stopping Appcore daemon..."
#	Pid=`ps -e | grep epmd | cut -f 1 -d " "`
#	kill -9 $Pid
	$ERL_PATH/bin/erl -name stopac_1@127.0.0.1 -noshell -eval 'rpc:call(list_to_atom("erlac@127.0.0.1"),init,stop,[])' -s erlang halt
	
	sleep 1
}

status()
{
	#PROG=$1
	PID=`pidof $1`
	if [ -n "$PID" ]; then
		echo "$1 ($PID) is running..."
		return 0
	fi
	echo "$1 is stopped..."
	return 1
}

stat()
{
	status epmd
	RETVAL=$?
	status platform_handler
	status oob_handler
	return $RETVAL
}

# See how we were called.
export PATH=$APPCORE_LIB_PATH:$PATH
export LD_LIBRARY_PATH=$APPCORE_LIB_PATH:$LD_LIB_PATH
export LD_LIBRARY_PATH
export HOME
export APPCORE_PATH=$HOME
export HEART_COMMAND

case "$1" in
	start)
		ERL_PARAMS=$ERL_RELEASE_PARAMS
		start
		;;
	stop)
		stop
		;;
	restart)
		stop
		ERL_PARAMS=$ERL_RELEASE_PARAMS
		start
		;;
	start_debug)
		ERL_PARAMS=$ERL_DEBUG_PARAMS
		start
		;;
	status)
		stat
		;;
	*)
		echo $"Usage: $0 {start|stop|restart|status}"
		;;
esac
exit $RETVAL
