#!/bin/bash
# openerp-server        This shell script takes care of starting and stopping
#                       OpenERP server
#
# chkconfig: 345 95 05
# description: OpenERP server
#
# pidfile: /var/run/openerp-server.pid
# config: /etc/openerp-server.conf

### BEGIN INIT INFO
# Provides: openerp-server
# Required-Start: postgresql
# Required-Stop: postgresql
# Should-Start: $network harddrake
# Default-Start: 345
# Short-Description: Launches the OpenERP server.
# Description: This startup script launches the OpenERP server.
### END INIT INFO

# Source function library.
. /etc/rc.d/init.d/functions

PIDFILE=/var/run/openerp/openerp-server.pid
LOCKFILE=/var/lock/subsys/openerp-server
LOGFILE=/var/log/openerp/openerp-server.log

OPTS="--pidfile=$PIDFILE --logfile=$LOGFILE"

prog="openerp-server"
desc="OpenERP Server Daemon"

# check if the openerp-server conf file is present, then use it
if [ -f /etc/openerp-server.conf ]; then
    OPTS="$OPTS -c /etc/openerp-server.conf"
fi

# Source function library
if [ -f /etc/init.d/functions ] ; then
    . /etc/init.d/functions
elif [ -f /etc/rc.d/init.d/functions ] ; then
    . /etc/rc.d/init.d/functions
else
 exit 0
fi

# check the existence of the openerp-server script
[ -z "/usr/bin/openerp-server" ] && exit 0

RETVAL=0

start() {
    if [ -d /etc/openerp/start.d ] ; then
        echo -n $"Preparing $desc: "
        run-parts --exit-on-error /etc/openerp/start.d
        RETVAL=$?
        echo
        [ $RETVAL -ne 0 ] && return $RETVAL
    fi
    
    echo -n $"Starting $desc ($prog): "
    daemon --user openerp --check openerp-server \
    "/usr/bin/setsid /usr/bin/openerp-server \
    -c /etc/openerp-server.conf \
    --pidfile=$PIDFILE \
    --logfile=$LOGFILE &"

    RETVAL=$?
    echo
    [ $RETVAL -eq 0 ] && touch $LOCKFILE
    return $RETVAL
}

stop() {
    echo -n $"Stopping $desc ($prog): "
    kill -TERM `cat $PIDFILE` > /dev/null 2>&1
    RETVAL=$?
    if [ $RETVAL -eq 0 ] ; then
        rm -f $LOCKFILE

        echo_success
        echo
    else
        echo_failure
        echo
    fi
    if [ -d /etc/openerp/stop.d ] ; then
        echo -n $"Clearing $desc: "
        run-parts /etc/openerp/stop.d
        echo
    fi
    return $RETVAL
}

restart() {
    stop
    start
}    

condrestart() {
    [ -e $LOCKFILE ] && restart || :
}

status() { 
    if [ -f $PIDFILE ] ; then
        checkpid `cat $PIDFILE`
        RETVAL=$?
        if [ $RETVAL -eq 0 ] ; then
            echo  $"$prog is running..."
        else
            echo  $"$prog is stopped"
        fi
    else
        echo  $"$prog is stopped"
    fi
    return $RETVAL
}

case "$1" in
start)
    start
    ;;

stop)
    stop
    ;;

restart|reload)
    restart
    ;;

condrestart)
    condrestart
    ;;

status)
    status
    ;;

probe)
    exit 0
    ;;

*)
    echo $"Usage: $0 {start|stop|status|restart|condrestart|reload}"
    exit 1
esac
