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

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

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

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

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

prog="tinyerp-server"
desc="TinyERP Server Daemon"

# check if the tinyerp-server conf file is present, then use it
if [ -f /etc/tinyerp-server.conf ]; then
    OPTS="$OPTS -c /etc/tinyerp-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 tinyerp-server script
[ -z "/usr/bin/tinyerp-server" ] && exit 0

RETVAL=0

start() {
    gprintf "Starting %s (%s): " "$desc" "$prog"
    daemon --user tinyerp --check tinyerp-server \
    "/usr/bin/setsid /usr/bin/tinyerp-server \
    -c /etc/tinyerp-server.conf \
    --pidfile=$PIDFILE \
    --logfile=$LOGFILE &"

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

stop() {
    gprintf "Stopping %s (%s): " "$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
		return $RETVAL
}    

restart() {
    stop
    start
}    

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

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

case "$1" in
start)
    start
    ;;

stop)
    stop
    ;;

restart|reload)
    restart
    ;;

condrestart)
    condrestart
    ;;

status)
    status
    ;;

probe)
    exit 0
    ;;

*)
    gprintf "Usage: %s {start|stop|status|restart|condrestart|reload}\n" "$0"
    exit 1
esac
