#! /bin/sh
#
# starts and stops the OML2 server
#     Written by Christoph Dwertmann
# Stop waiting logic adapted from Debian's /etc/init.d/apache2

### BEGIN INIT INFO
# Provides:          oml2-server
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start daemon at boot time
# Description:       Enable service provided by daemon.
### END INIT INFO

PATH=/sbin:/usr/sbin:/bin:/usr/bin
DESC="OML2 Measurements Collection Server"
NAME=oml2-server
DAEMON=/usr/bin/$NAME
PIDFILE=/var/run/$NAME.pid
FIN_WAIT_TO=`cat /proc/sys/net/ipv4/tcp_fin_timeout`

test -x $DAEMON || exit 0

umask 022

if [ -f /etc/default/oml2-server ]; then
    . /etc/default/oml2-server
fi

. /lib/lsb/init-functions

start(){
    log_daemon_msg "Starting $DESC" "$NAME" || true
    start-stop-daemon --start --quiet --background --pidfile $PIDFILE --make-pidfile --exec $DAEMON -- $OPTS
    log_end_msg $? || true

}

stop(){
    log_daemon_msg "Stopping $DESC" "$NAME" || true
    start-stop-daemon --stop --quiet --oknodo --pidfile $PIDFILE
    log_end_msg $? || true
}


pidof_oml2server(){
    if [ -e "$PIDFILE" ]; then
	if pidof $NAME | tr ' ' '\n' | grep -w $(cat $PIDFILE); then
	    return 0
	fi
    fi
    return 1
}

wait_stop(){
    PIDTMP=$(pidof_oml2server) || true
    if kill -0 "${PIDTMP:-}" 2> /dev/null; then
	PID=$PIDTMP
    fi

    stop

    if [ -n "${PID:-}" ]; then
	FAILED=0
	i=0
	# Wait for the process to terminate
	while kill -0 "${PID:-}" 2> /dev/null;  do
	    if [ $i = '60' ]; then
		FAILED=1
		break;
	    else
		if [ $i = '0' ]; then
		    log_action_begin_msg "Waiting for $NAME to terminate" || true
		else
		    log_action_cont_msg "." || true
		fi
		i=$(($i+1))
		sleep 1
	    fi
	done
	log_action_end_msg $FAILED || true
    fi
    # Wait for the kernel to have cleaned up FIN_WAIT sockets (#1262)
    FIN_WAIT_TO=$((FIN_WAIT_TO-i))
    log_action_msg "Waiting for FIN_WAIT sockets (${FIN_WAIT_TO}s).." || true
    sleep ${FIN_WAIT_TO}
}

case "$1" in
    start)
	start
	;;
    stop)
	stop
	;;
    restart|force-reload)
	wait_stop
	start
	;;
    status)
	status_of_proc -p $PIDFILE $DAEMON $NAME && exit 0 || exit $?
	;;
    *)
	log_action_msg "Usage: /etc/init.d/$NAME {start|stop|restart|force-reload|status}" || true
	exit 1
esac

exit 0

# vim: sw=4
