#!/bin/bash
### BEGIN INIT INFO
# Provides:          mediacentric-indexer
# Required-Start:    $local_fs $remote_fs $network $syslog
# Required-Stop:     $local_fs $remote_fs $network $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: starts Mediacentric's modules
# Description:       starts Mediacentric'w modules using start-stop-daemon
### END INIT INFO

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
NAME=mediacentric
DESC=MediaCentric
export MEDIACENTRIC_HOME="/opt/bertin/mediacentric"
PATH_MODULES="/opt/bertin/mediacentric/modules"
CNF=$MEDIACENTRIC_HOME/conf/mediacentric.properties
SCRIPTNAME=/etc/init.d/$NAME
module=indexer

MAX_WAIT=20

user_exec() {
	su mediacentric -c "$*"
}

remote_exec() {
	echo curl http://$1:8383/services/$2/$3 
	rep=`curl http://$1:8383/services/$2/$3 2>/dev/null`
	if [ $? -ne 0 ]; then 
		echo "Failed to contact service agent for host $1"
		return 2
	fi
	echo -n "$3 $2 on host $1 : "
	if [ $rep -eq 0 ]; then echo "OK"; else echo "NOK"; fi
	return $rep
}

check_solr_is_up() {
	srv=`grep "^$1 *=" $CNF | sed -e 's/^.*= *//'`
	r=0
	if [ ! -z "$srv" ]; then 
		remote_exec $srv idx status
		r=$?
		if [ $r -ne 0 ]; then   # wait a bit and retry
			echo -n "Waiting $MAX_WAIT for $1 instance to be up"
			n=0
			while [ $n -lt $MAX_WAIT ]; do
				echo -n "."
				sleep 1 
				remote_exec $srv idx status
				r=$?
				if [ $r -eq 0 ]; then break; fi
				n=$[ n + 1 ]
			done
		fi
		if [ $r -ne 0 ]; then 
			echo "ERROR : $1 instance not started !";
		fi
	fi
	return $r
}

wait_for_solr() {
	echo -n "checking if solr is up ."
	check_solr_is_up solr.host
	ret=$?
	if [ $ret -eq 0 ]; then
		check_solr_is_up ttl.solr.host
		ret=$?
	fi
	return $ret
}


d_status() {
        user_exec $PATH_MODULES/$module/bin/module_launcher.sh status
}

d_start() {
	## refuse to start indexer until solr is up
#	wait_for_solr 
	if [ $? -eq 0 ]; then 
		user_exec $PATH_MODULES/$module/bin/module_launcher.sh start
	fi
}

d_stop() {
	user_exec $PATH_MODULES/$module/bin/module_launcher.sh stop
}

action=$1
shift 1
case $action in
	"start") d_start ;;
	"stop") d_stop ;;
	"status") d_status ;;
	"restart")
		d_stop 
		sleep 1
		d_start
		;;
	*) echo "usage : $0 <start|stop|status>";;
esac
