#!/bin/sh
# Startup script for a oood server based on zope startup script
#
# chkconfig: 5 99 1
# description: oood, the standalone server for converting various types of docs to/from OpenOffice format

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

NAME="oood"
USER=oood
HOME=/var/lib/oood
RUNDIR=/var/run/oood
LOCKFILE=$RUNDIR/server_pid.lock
PIDFILE=$LOCKFILE

start() {
  if [ -f $LOCKFILE ] ; then
    gprintf "Another instance of %s is running (lockfile exists)." "$NAME"
    echo_failure
    echo
    exit 4
  fi

  gprintf "Starting %s: " "$NAME"
  # Initialize the Pool
  su --login $USER --command="python $HOME/start.py --init > /dev/null 2>&1 /dev/null"
  # Start the server in the background
  su --login $USER --command="python $HOME/runserw.py --start > /dev/null &"
  sleep 10 # Safe sleep to let the server create its lockfile
           # Warning: this trick should be replaced by a stronger mechanism,
           #   because under heavy load, the server can take several tenth of
           #   seconds to start. This case should be handled in runserw.py script.
  if [ -f $PIDFILE ]; then
    echo_success
  else
    gprintf "%s is not running (no pid file found)." "$NAME"
    su --login $USER --command="python $HOME/start.py --flush > /dev/null 2>&1 /dev/null"
    echo_failure
  fi
  echo
}


stop() {
  if [ ! -f $LOCKFILE ] ; then
    gprintf "%s is not running (no lockfile found)." "$NAME"
    echo_failure
  else
    gprintf "Stopping %s daemon: " "$NAME"
    su --login $USER --command="python $HOME/runserw.py --stop" && echo_success || echo_failure
  fi
  # Clean up in any case
  su --login $USER --command="python $HOME/start.py --flush > /dev/null 2>&1 /dev/null"
  echo
}


status() {
  echo
  su --login $USER --command="python $HOME/runserw.py --status"
  echo
  su --login $USER --command="python $HOME/start.py   --status"
  echo
}


case "$1" in
  start)
    touch /var/lock/subsys/$NAME
    start
    ;;

  stop)
    stop
    rm -f /var/lock/subsys/$NAME
    ;;

  restart)
    stop
    start
    ;;

  status)
    status
    ;;
  *)

  gprintf "Usage: %s\n" "$0 {start|stop|restart|status}"
  exit 1

esac

exit
