#! /bin/sh
### BEGIN INIT INFO
# Provides:          local-agent
# Required-Start:    $all
# Required-Stop:     $all
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start and stop local-agent daemon
# Description:       Controls the main local-agent daemon "local-agent"
#                    
### END INIT INFO

# PATH should only include /usr/* if it runs after the mountnfs.sh script
PATH=/sbin:/usr/sbin:/bin:/usr/bin

DESC="local-agent"
NAME=local-agent
DAEMON=/usr/sbin/$NAME
PIDFILE=/var/run/$NAME.pid
USER="local-agent:local-agent"
CONF_PATH=/etc/sphinx

# Exit if the package is not installed
[ -x "$DAEMON" ] || exit 0
[ -f "/etc/sphinx/sphinxd.cfg" ] || exit 0

# Read configuration variable file if it is present
[ -r /etc/default/$NAME ] && . /etc/default/$NAME

# Load the VERBOSE setting and other rcS variables
. /lib/init/vars.sh

# Define LSB log_* functions.
# Depend on lsb-base (>= 3.2-14) to ensure that this file is present
# and status_of_proc is working.
. /lib/lsb/init-functions

apply_permissions()
{
	chown $USER $CONF_PATH/*
	return $?
}

checkpid()
{
	[ -f $PIDFILE ] || return 1
	pid=`cat $PIDFILE`
	[ -d /proc/$pid ] && return 0
	return 1
}

do_start()
{
	apply_permissions
	$DAEMON

	RETVAL=$?
	sleep 1
	return $RETVAL;
}

do_stop()
{

	pid=`cat $PIDFILE`

# TODO: make serveral termination attempts
	kill $pid

	sleep 1
	rm -f $PIDFILE
	checkpid
	return $?
}

do_restart()
{
	do_stop
	do_start
	RETVAL=$?
	return $RETVAL
}

start_daemon()
{
	echo -n "Starting $DESC: "
	do_start
	checkpid

	if [ $? -eq 1 ]; then
		rm -f $PIDFILE
		echo "failed."
		exit 1
	fi

	echo "done."
}

stop_daemon()
{
	checkpid

	if [ $? -eq 1 ]; then
		exit 0
	fi

	echo -n "Stopping $DESC: "
	do_stop

	if [ $? -eq 0 ]; then
		echo "failed."
		exit 1
	fi

	echo "done."
}

restart_daemon()
{
	echo -n "Restarting $DESC: "
	do_restart
	checkpid
	
	if [ $? -eq 1 ]; then
		rm -f $PIDFILE
		echo "failed."
		exit 1
	fi
	echo "done."
}

status_daemon()
{
	echo -n "Checking $DESC: "
	checkpid

	if [ $? -eq 1 ]; then
		echo "stopped."
		exit 1
	else
		echo "running."
		exit 0
	fi
}

case "$1" in
  start) start_daemon ;;
  stop)	 stop_daemon ;;
  status) status_daemon ;;
  restart|force-reload) restart_daemon ;;
  *)
	N=/etc/init.d/$DESC
	echo "Usage: $N {start|stop|restart|force-reload|status}" >&2
	exit 1
	;;
esac

exit 0
