#!/bin/sh
#
# Starts kwilt-index.
#

source "/etc/features.conf"

PIDFILE="/var/run/kwilt-index.pid"

start() {
	local VERBOSITY=
	if [ "$ENABLE_DEBUG" == "1" ]; then
		VERBOSITY="-V7"
	elif [ "$ENABLE_LOGGING" == "0" ]; then
		VERBOSITY="-V0"
	fi
	echo -n "Starting kwilt-index: "
	/sbin/kwilt-index -d -p ${PIDFILE} ${VERBOSITY}
	echo "OK"
}

stop() {
	if [ ! -f ${PIDFILE} ]; then
		echo "kwilt-index is not running"
		exit 1;
	fi

	PID=`cat ${PIDFILE}`
	if ! kill -0 ${PID} 2>/dev/null ; then
		echo "kwilt-index is stopped, but pid file exists: $PIDFILE"
		exit 2;
	fi

	echo -n "Stopping kwilt-index: "
	kill -INT ${PID} 2>/dev/null
	WAITED=0
	while [ -f ${PIDFILE} ] && [ "${WAITED}" -lt "10" ]; do
		sleep 1
		WAITED=$((WAITED + 1))
	done

	if [ "${WAITED}" == "5" ]; then
		kill -KILL ${PID} 2>/dev/null
		rm -f ${PIDFILE}
	fi

	echo "OK"
}

restart() {
	stop
	start
}

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

exit $?

