#!/bin/sh
# initscript for NHSD_INIT_VERSION
# <frank@opengroupware.org>
# 
# chkconfig: 2345 99 99
# description: Network hotsync daemon - NHSD_INIT_VERSION
#
# processname: NHSD_INIT_VERSION
# pidfile: /var/run/NHSD_INIT_VERSION.pid
#
# source function library
. /etc/rc.d/init.d/functions

RETVAL=0
PROG="NHSD_INIT_VERSION"
USER="ogo"
DIR="NHSD_INIT_PREFIX"
BIN="NHSD_INIT_PREFIX/sbin/NHSD_INIT_VERSION"
PID_FILE="/var/run/NHSD_INIT_VERSION.pid"
LOGERR="/var/log/opengroupware/NHSD_INIT_VERSION-err.log"
LOGOUT="/var/log/opengroupware/NHSD_INIT_VERSION-out.log"
PLIST="nhsd"
SLEEP="3"

# pull in sysconfig settings
# 
[ -f /etc/sysconfig/ogo-nhsd ] && . /etc/sysconfig/ogo-nhsd

sleep_dots()
{
  for (( s=1; s<=${SLEEP}; s++ )); do
    sleep 1
    echo -en "."
  done
}

start()
{
  PID=`/sbin/pidof "${BIN}"`
  if [ -n "${PID}" ]; then
    echo -en "${PROG} already runs!" && failure
    echo -en "\n"
  else
    echo -en $"Starting ${PROG} "
    su - ${USER} -s /bin/bash -c "export PGCLIENTENCODING=${PGCLIENTENCODING}; exec ${BIN} 2>>${LOGERR} 1>>${LOGOUT} &"
    sleep_dots
    echo -en ":"
    echo $! > ${PID_FILE}
    PID=`/sbin/pidof "${BIN}"`
    if [ -n "${PID}" ]; then
      touch /var/lock/subsys/${PROG} && success
    else
      rm -f ${PID_FILE}
      rm -f /var/lock/subsys/${PROG} && failure
    fi
    echo
  fi
}

status()
{
  PID=`/sbin/pidof "${BIN}"`
  if [ -n "${PID}" ]; then
    echo -en "${PROG} is running -> ${PID}" && success
    echo -en "\n"
  else
    echo -en "${PROG} isn't running." && failure
    echo -en "\n"
  fi
}

stop()
{
  echo -en $"Stopping ${PROG} "
  if [ -f "${PID_FILE}" ] ; then
    PID=`cat ${PID_FILE}`
    if [ "`kill ${PID} 2>>${LOGERR} 1>>${LOGOUT}`" ] ; then
      sleep_dots
      echo -en ":"
      success
      rm -f ${PID_FILE}
      rm -f /var/lock/subsys/${PROG}
    else
      PID="`pgrep -f ${BIN}`"
      kill -9 ${PID} 2>/dev/null && sleep_dots && echo -en ":" && success || failure
      rm -f ${PID_FILE}
      rm -f /var/lock/subsys/${PROG}
    fi
  else
    killproc ${PROG}
    RETVAL=$?
    echo -en "\n"
    if [ ${RETVAL} -eq 0 ]; then
      rm -f /var/lock/subsys/${PROG}
      rm -f ${PID_FILE}
    fi
  return ${RETVAL}
  fi
  echo
}

showdefaults()
{
  su - ${USER} -s /bin/bash -c "exec Defaults read ${PLIST}"
}

restart()
{
  stop
  start
}

[ -x ${BIN} ] || exit 0

# See how we were called.
case "$1" in
  start)
  start
  ;;
  stop)
  stop
  ;;
  restart)
  restart
  ;;
  status)
  status
  ;;
  showdefaults)
  showdefaults
  ;;
  *)
  echo $"Usage: $0 {start|stop|restart|showdefaults|status}"
  exit 1
esac

exit 0