#!/bin/bash
###########################################################################
# Eole NG - 2007
# Copyright Pole de Competence Eole  (Ministere Education - Academie Dijon)
# Licence CeCill  cf /root/LicenceEole.txt
# eole@ac-dijon.fr
#
# zephir
#
# script de démarrage du service backend Zephir
#
###########################################################################
# XXX Attention, ce script est utilisé par zephir-client pour déterminer
# si on est sur le module Zéphir
#
###########################################################################
#
### BEGIN INIT INFO
# Provides:          zephir
# Required-Start:    $local_fs $remote_fs
# Required-Stop:     $local_fs $remote_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: serveur bas niveau zephir
# Description:     : serveur de l'application de gestion de parc zephir
### END INIT INFO
#
# Author:	Equipe Eole <eole@ac-dijon.fr>.
#
## 28/02/2006
#

PROGRAM=/bin/false
RUNLEVEL=3
PIDFILE=/var/run/zephir_backend.pid
LOCKFILE=/var/lock/zephir_backend
PG_VERSION=8.4
PG_SERVICE=postgresql-$PG_VERSION
##
NAME=zephir
DESC="Backend Zéphir"
DAEMON=/usr/bin/twistd
DAEMON_ARGS="--pidfile $PIDFILE --syslog --umask 022 -o zephir_backend"
ZEPHIR_DIR=/usr/share/zephir
TEMPLATE_DIR=$ZEPHIR_DIR/monitor/agentmanager/templates
# NOSCAN : si argument "noscan" après start, on démarre le serveur sans
# la boucle de vérification des timeouts (évite les ralentissements pendant
# l'instanciation, la restauration, ...)
NOSCAN=0

. /lib/lsb/init-functions

[ -f /etc/eole/config.eol ] || exit 0

cd $ZEPHIR_DIR

if [ ! -f /usr/lib/python2.7/dist-packages/twisted/plugins/eole_zephir.py ]
then
	echo -e "le service n'est pas installé.\n"
	log_end_msg 1
fi

do_kill() {
	local sig pid killretcode
	sig=$1
	pid=$2
	killretcode=$3
	[ -n "$pid" ] || return 1
	kill -$sig $pid 2>/dev/null
	[ $? -eq $killretcode ]
}

do_wait() {
	local n sig pid killretcode waitmsg
	if [ "$1" = 'start' ]; then
		killretcode=0
		waitmsg='start'
	elif [ "$1" = 'stop' ]; then
		killretcode=1
		waitmsg="die"
	fi
	if [ -f "$PIDFILE" ]; then
	    pid=$(cat $PIDFILE)
	elif [ "$1" = 'stop' ]; then
		return 0
	fi
	sig=0
	n=1
	while ! do_kill "$sig" "$pid" "$killretcode" ; do
		if [ $n -eq 2 ]; then
			echo "waiting for process to $waitmsg" >&2
		fi
		if [ "$action" = 'stop' -a $n -eq 11 ]; then
			echo "giving up on pid $pid with kill -0; trying -9"
			sig=9
		fi
		if [ $n -gt 20 ]; then
			echo "giving up on pid $pid"
			break
		fi
		n=$(($n+1))
		sleep 1
		if [ -z "$pid" -a -f "$PIDFILE" ]; then
		    pid=$(cat "$PIDFILE")
		fi
	done
}

do_start()
{
	# postgresql-8.3 ne restart pas bien !
	pidof postgres > /dev/null
	if [ $? -ne 0 ];then
		CreoleService $PG_SERVICE start &>/dev/null
	fi
	# fin du hack

	# Return
	#   0 if daemon has been started
	#   1 if daemon was already running
	#   2 if daemon could not be started
    # si les nouveaux agents sont installés,
    # on recompile les templates Cheetah
	log_begin_msg "Starting $DESC: $NAME"
	start-stop-daemon --start --quiet --pidfile $PIDFILE --startas $DAEMON --test > /dev/null \
		|| return 1
    if [ -d $TEMPLATE_DIR ]
    then
        cd $TEMPLATE_DIR
        make # >/dev/null
        cd $ZEPHIR_DIR
    fi
    # on recopie les données statiques si nécessaire
    if [ ! -f /var/lib/zephir/sites/stylesheet.css ]
    then
        cp -rf monitor/static/*.css /var/lib/zephir/sites/
    fi
    # images
    unset echo
    cp -rf monitor/static/img /var/lib/zephir/sites/
    python /usr/share/zephir/utils/parse_logs.py
    start-stop-daemon --start -d $ZEPHIR_DIR --exec $DAEMON -- $DAEMON_ARGS > /dev/null
    touch $LOCKFILE
    do_wait 'start'
    [ $? -eq 0 ] || return 2
    # on initialise la vérification du timeout
    if [ $NOSCAN -eq 0 ]
    then
        python backend/init_scan.py >/dev/null &
    fi
    return 0
}


do_stop()
{
	# Return
	#   0 if daemon has been stopped
	#   1 if daemon was already stopped
	#   2 if daemon could not be stopped
	#   other if a failure occurred
	log_begin_msg "Stopping $DESC: $NAME"
	start-stop-daemon --stop --quiet --oknodo --retry=TERM/30/KILL/5 --pidfile $PIDFILE
	RETVAL="$?"
	[ "$RETVAL" = 2 ] && return 2
	# Wait for children to finish too if this is a daemon that forks
	# and if the daemon is only ever run from this initscript.
	# If the above conditions are not satisfied then add some other code
	# that waits for the process to drop all resources that could be
	# needed by services started subsequently.  A last resort is to
	# sleep for some time.
	do_wait 'stop'
	start-stop-daemon --stop --quiet --oknodo --retry=0/30/KILL/5 --pidfile $PIDFILE
	[ "$?" = 2 ] && return 2
	# Many daemons don't delete their pidfiles when they exit.
	rm -f $PIDFILE
    rm -f /var/spool/uucp/lock &>/dev/null
	return "$RETVAL"
}


[ "$2" == "noscan" ] && NOSCAN=1

case "$1" in
  start)
	do_start
	case "$?" in
		0|1) log_end_msg 0 ;;
		2) log_end_msg 1 ;;
	esac
	;;
  stop)
	do_stop
	case "$?" in
		0|1) log_end_msg 0 ;;
		2) log_end_msg 1 ;;
	esac
	;;
  status)
	status_of_proc -p "$PIDFILE" "$DAEMON" "$NAME" && exit 0 || exit $?
	;;
  restart|force-reload)
	do_stop
	case "$?" in
	  0|1)
        sleep 1
		do_start
		case "$?" in
			0) log_end_msg 0 ;;
			1) log_end_msg 1 ;; # Old process is still running
			*) log_end_msg 1 ;; # Failed to start
		esac
		;;
	  *)
		# Failed to stop
		log_end_msg 1
		;;
	esac
	;;
  *)
	echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload}" >&2
	exit 3
	;;
esac

exit 0
