#!/bin/sh
#

# chkconfig: 345 41 59
# description: Mandriva Server Setup Web interface

### BEGIN INIT INFO
# Provides: mss-www
# Required-Start: $network $mss-agent
# Required-Stop: $network
# Default-Start: 3 4 5
# Default-Stop: 0 1 6
# Short-Description: ROSA Server Setup Web interface
# Description: Wizard for MDS/Pulse 2 setup and server stacks installation
### END INIT INFO

. /etc/rc.d/init.d/functions
[ -r /etc/sysconfig/i18n ] && . /etc/sysconfig/i18n
export LC_ALL
export LANG

prog=mss-www
python_version=`python -c 'import sys; print(".".join(map(str, sys.version_info[:2])))'`

####################################
# Configuration
#
HOST=0.0.0.0
PORT=8000
USER=mss
GROUP=mss
SSL=1
SSL_CRT=/etc/mss/ssl/localhost.crt
SSL_KEY=/etc/mss/ssl/localhost.key
# Your path.
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
# Location of the webserver.py file
BASEDIR=/usr/lib/python$python_version/site-packages/mss/www/
DAEMON=manage.py
# PID file to be created. It must match with the PID file in the
# configuration module.
PIDFILE=/var/run/$prog.pid
#
####################################

test -f $BASEDIR$DAEMON || exit 0
test -f /usr/bin/python || exit 0

#set -e
CWD=`pwd`

function start () {
    printf "Starting %s: " "$prog"
    if [ -f /var/lock/subsys/$prog ]; then
	    printf "%s is already running" "$prog" && success
    else
        if [ $SSL == 1 ]; then
            [ ! -f $SSL_CRT ] && echo "SSL certificate not found" && failure
            [ ! -f $SSL_KEY ] && echo "SSL private key not found" && failure            
            SSL_OPTIONS="ssl_certificate=$SSL_CRT ssl_private_key=$SSL_KEY"
        else
            SSL_OPTIONS=""
        fi
        cd $BASEDIR
        /usr/bin/python $DAEMON runcpserver host=$HOST port=$PORT server_group=$GROUP \
            server_user=$USER pidfile=$PIDFILE daemonize=true $SSL_OPTIONS
        # wait pid file to be created
        sleep 1
        touch /var/lock/subsys/$prog
        [ -f $PIDFILE ] && success || failure
    fi
    echo
}

function stop () {
    printf "Stopping %s: " "$prog"
    if [ -f /var/lock/subsys/$prog ]; then
        cd $BASEDIR
        /usr/bin/python $DAEMON runcpserver pidfile=$PIDFILE stop
        if [ "$?" == "0" ]; then
            sleep 1
    	    [ -f /var/lock/subsys/$prog ] && rm -f /var/lock/subsys/$prog
    	fi
        [ ! -f $PIDFILE ] && success || failure
    else
	    printf "%s is not running" "$prog" && success
    fi
    echo
}

case "$1" in
    start)
	start
	;;
    stop)
	stop
	;;
    restart)
	stop
	start
	;;
    reload)
	stop
	start
	;;
    status)
	status -p $PIDFILE
	;;
    *)
	printf "Usage: $0 {start|stop|restart}\n"
	exit 1
esac

cd $CWD

exit 0
