#!/bin/sh

### BEGIN INIT INFO
# Provides:		openerp-server
# Required-Start:	$remote_fs $syslog
# Required-Stop:	$remote_fs $syslog
# Should-Start:		$network
# Should-Stop:		$network
# Default-Start:	2 3 4 5
# Default-Stop:		0 1 6
# Short-Description:	Enterprise Resource Management software
# Description:		Open ERP is a complete ERP and CRM software.
### END INIT INFO

PATH="/sbin:/bin:/usr/sbin:/usr/bin"
DAEMON="::openerp.instdir::/server/openerp-server"
PROGNAME="openerp-server"
DESC="OpenErp Server"
DEFAULT_FILE="/etc/default/$PROGNAME"
PIDFILE="/var/run/$PROGNAME.pid"

# configurable variables (see $DEFAULT_FILE)
#
ENABLED="false"
OPTIONS=""
USER="openerp"
CONFIG="::openerp.instdir::/etc/openerp-server.conf"
LOGFILE="/var/log/openerp/openerp-server.log"


test -x ${DAEMON} || exit 0

set -e

do_start () {
  	$ENABLED || return 0

	local dir=`dirname "$LOGFILE"`
	[ -d "$dir" ] || {
		mkdir "$dir" || return $?
		chown $USER:root "$dir" || return $?
	}

	dir=`dirname $PIDFILE`
	[ -d "$dir" ] || {
		mkdir "$dir" || return $?
	}

        log_daemon_msg "Starting $DESC"
	start-stop-daemon --start --quiet --pidfile $PIDFILE \
		--chuid ${USER} --background --make-pidfile --exec ${DAEMON} \
		-- --config=${CONFIG} --logfile=${LOGFILE} $OPTIONS
	local ret=$?
	log_end_msg $ret
	return $ret
}

do_stop () {
  	$ENABLED || return 0
        log_daemon_msg "Stopping $DESC"
	start-stop-daemon --stop --quiet --pidfile $PIDFILE --oknodo
	local ret=$?
	log_end_msg $ret
	return $ret
}

# (MAIN)



test -x $DAEMON || exit 0

. /lib/lsb/init-functions
. /etc/default/rcS

export PATH="${PATH:+$PATH:}/usr/sbin:/sbin"


[ -s $DEFAULT_FILE ] && {
    . $DEFAULT_FILE
    case "x$ENABLED" in
        xtrue|xfalse)
		;;
        *)	log_failure_msg "$DEFAULT_FILE: ENABLED must be 'true' or 'false';"
		log_failure_msg "daemon not started"
		exit 1
		;;
    esac
}


case "$1" in
  start)
  	do_start ;;
  stop)
  	do_stop ;;
  restart)
  	do_stop
	do_start
	;;
  reload|force-reload)
	do_stop
	do_start
	;;
  status)
	do_stat
	;;
  *)
	echo "usage: /etc/init.d/$PROGNAME {start|stop|reload|force-reload|restart|status}"
	exit 1
esac

exit 0
