#! /bin/bash
### BEGIN INIT INFO
# Provides:          arv
# 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: arv initscript
# Description:       demarrage/arret de ARV
#                    des Modules EOLE
### END INIT INFO
#
# Author:    Equipe EOLE <eole@ac-dijon.fr>.
#

set -e

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
PYTHONPATH=/usr/share/
DESC="Serveur ARV"
NAME=arv
DAEMON=/usr/bin/twistd
DAEMON_ARGS="-noy /usr/share/arv/website.tac"
PIDFILE=/var/run/arv/$NAME.pid
SCRIPTNAME=/etc/init.d/$NAME
ERRORFILE=/var/log/arv/error.log

export PYTHONPATH

OCF_ROOT=/usr/lib/ocf
. ${OCF_ROOT}/resource.d/heartbeat/.ocf-shellfuncs
. /lib/lsb/init-functions

# Gracefully exit if the package has been removed.
test -e $DAEMON || exit 0

if [ ! -d /var/run/arv ];then
    mkdir -p /var/run/arv
    chown nobody /var/run/arv
fi

#
#    Function that starts the daemon/service.
#
d_start() {
    log_begin_msg "Starting $DESC: $NAME"
    if [ -f $PIDFILE ]
    then
        log_daemon_msg "$PIDFILE exists"
        return $OCF_SUCCESS
        #log_end_msg $?
    else
        start-stop-daemon -b --start --exec $DAEMON -- $DAEMON_ARGS --pidfile $PIDFILE --logfile /var/log/arv/$NAME.log 2>> $ERRORFILE
        if [ $? -eq 0 ]
        then
            i=0
            while [ ! -f $PIDFILE ]
            do
                sleep 1
                if [ $i -eq 3 ]
                then
                    return $OCF_ERR_GENERIC
                fi
                let $[ i+=1 ]
            done
            return $OCF_SUCCESS
        else
            return $OCF_ERR_GENERIC
        fi
        #log_end_msg $?
    fi
}

#
#    Function that stops the daemon/service.
#
d_stop() {
    log_begin_msg "Stopping $DESC: $NAME"
    if [ -f $PIDFILE ]
    then
        start-stop-daemon --stop --quiet -o --pidfile $PIDFILE
        sleep 1
    fi
    proclist=$(ps axf|grep -e "twistd"|grep -e "$NAME"|grep -v "grep"|awk -F" " '{print $1}')
    if [ "$proclist" != "" ]
    then
        for procid in "$proclist"
        do
            kill -9 $procid
        done
    fi
    if [ -f $PIDFILE ]
    then
        rm $PIDFILE
    fi
    return $OCF_SUCCESS

        # pour le restart
        #log_end_msg 0
}

d_status() {
    if [ ! -f $PIDFILE ]
    then
        echo "$DESC est arrêté"
        exit $OCF_NOT_RUNNING
    fi
    pid=`cat $PIDFILE`
    kill -0 $pid >/dev/null 2>&1
    if [ $? -eq 0 ]
    then
        echo "$DESC (pid $pid) est actif ..."
        exit $OCF_SUCCESS
    fi
    echo "$DESC est arrêté"
    exit $OCF_NOT_RUNNING
}

d_monitor() {
    d_status
}

case "$1" in
  start)
    d_start
    ;;
  stop)
    d_stop
    ;;
  restart|force-reload)
    d_stop
    sleep 4
    d_start
    ;;
  status)
    d_status
    ;;
  monitor)
    d_monitor
    ;;

  *)
    echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload}" >&2
    exit 3
    ;;
esac

exit 0
