#!/bin/bash
#
# metadata-service        Startup script for the metadata service
#
# chkconfig: 235 90 10
# description: The metadata service is a powerful combination of an \
#             indexer and a search engine for all kinds of documents.
# config: /etc/metadata-service.conf
# pidfile: /var/run/metadata-service.pid

# Basic support for the Linux Standard Base Specification 1.0.0 (to be used by
# insserv for exemple)
### BEGIN INIT INFO
# Provides: MetadataService
# Required-Start: $syslog
# Required-Stop:
# Default-Start: 2 3 5
# Default-Stop:
# Description: Manages the metadata service
### END INIT INFO

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

# Path to the msctl script, server binary, and short-form for messages.
msctl=${MSCTL-/usr/bin/msctl}
prog=metadata-service
lockfile=${LOCKFILE-/var/lock/subsys/metadata-service}
pidfile=${PIDFILE-/var/run/metadata-service.pid}
RETVAL=0

savepid() {
        $msctl getpid > $pidfile
}

extendedstatus() {
        $msctl status
}

mystatus() {
	local base=${1##*/}
	local pid

	# First try "msctl" and we trap errors to stderr away
	pid=`$msctl getpid 2> /dev/null`
	if [ -n "$pid" ]; then
		echo $"${base} (pid $pid) is running..."
		return 0
	fi

	# Next try "/var/run/*.pid" files
	if [ -f /var/run/${base}.pid ] ; then
		read pid < /var/run/${base}.pid
		if [ -n "$pid" ]; then
			echo $"${base} dead but pid file exists"
			return 1
		fi
	fi
	# See if /var/lock/subsys/${base} exists
	if [ -f /var/lock/subsys/${base} ]; then
		echo $"${base} dead but subsys locked"
		return 2
	fi
	echo $"${base} is stopped"
	return 3
}

start() {
	echo -n $"Starting $prog "
	daemon $msctl start $OPTIONS
	RETVAL=$?
	echo
	[ $RETVAL = 0 ] && ( touch ${lockfile} ; savepid ) # FIXME here is where we would add the msctl getpid to save the pid to /var/run/ms.pid
	return $RETVAL
}
stop() {
	echo -n $"Stopping $prog "
	$msctl stop > /dev/null 2>&1 < /dev/null
	ret=$?
	if [ $ret -eq 0 ]
	then
		echo_success
	else
		echo_failure
	fi
	echo
	
	RETVAL=$ret
	[ $RETVAL = 0 ] && rm -f ${lockfile} ${pidfile}
}

# See how we were called.
case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	status)
		mystatus $prog
		RETVAL=$?
		;;
	fullstatus)
		$msctl status
		RETVAL=$?
		;;
	restart)
		stop
		start
		;;
	*)
		echo $"Usage: $prog {start|stop|restart|status|fullstatus|help}"
		exit 1
esac

exit $RETVAL
