#!/bin/sh
#
# PROVIDES: jchkmail
# BEFORE: mail
# REQUIRE: LOGIN

JCHKMAIL_HOME=/usr/pkg/sbin

JCHKMAIL_BIN=j-chkmail

OPTIONS=" "

PIDFILE=/var/jchkmail/j-chkmail.pid
SOCKFILE=/var/jchkmail/j-chkmail.sock

cleanpidfile ()
{
  run=`ps -axu | grep $JCHKMAIL_BIN  | grep -c -v grep`
  if [ "$run" != "0" ] ; then
    if [ -f $PIDFILE ] ; then
      echo "Removing old PID file..."
      rm -f $PIDFILE
    fi
  fi
}

cleansockfile ()
{
  run=`ps -axu | grep $JCHKMAIL_BIN  | grep -c -v grep`
  if [ "$run" != "0" ] ; then
    if [ -r $SOCKFILE ] ; then
      echo "Removing old SOCK file..."
      rm -f $SOCKFILE
    fi
  fi
}

removesockfile ()
{
  if [ -r $SOCKFILE ] ; then
    echo "Removing old SOCK file..."
    rm -f $SOCKFILE
  fi
}

start ()
{
  cleanpidfile
  cleansockfile

  if [ -f $JCHKMAIL_HOME/$JCHKMAIL_BIN ] ; then
    echo "Starting $JCHKMAIL_BIN...."
    $JCHKMAIL_HOME/$JCHKMAIL_BIN $OPTIONS 
    echo ".... $JCHKMAIL_BIN started !"
  fi
}

stop () {
  echo "Stopping $JCHKMAIL_BIN...."
  i=10
  while [ $i -gt 0 -a -f $PIDFILE ]; do
    kill `head -1 $PIDFILE`
    i=`expr $i - 1`
    sleep 1
  done
  cleanpidfile
  cleansockfile
  echo " OK !"
}

restart () 
{
  stop
  sleep 2
  start
}

reload ()
{
  if [ -f  "$PIDFILE" ]; then
    kill -HUP `head -1 $PIDFILE`
  fi
  removesockfile
}

dumpstats ()
{
  if [ -f  "$PIDFILE" ]; then
    kill -USR1 `head -1 $PIDFILE`
  fi
}

clearstats ()
{
  if [ -f  "$PIDFILE" ]; then
    kill -USR2 `head -1 $PIDFILE`
  fi
}

case "$1" in
'start')
	start
	;;

'stop')
	stop
	;;

'restart')
	restart
	;;

'reload')
  reload
  ;;

'dumpstats')
  dumpstats
  ;;

'clearstats')
  clearstats
  ;;
*)
	echo "Usage: $0 { start | stop | restart | reload | dumpstats | clearstats }"
        cat <<EOF
start      - start j-chkmail
stop       - stop j-chkmail
restart    - stop and start j-chkmail
reload     - reload j-chkmail configuration files 
             (send SIGHUP to the daemon)
dumpstats  - dump internal counters
             (send SUGUSR1 to the daemon)
clearstats - reset internal counters
             (send SIGUSR2 to the daemon)
help       - this screen

EOF
	exit 1
	;;
esac

exit 0

