#!/bin/sh

# Basic support for IRIX style chkconfig
# chkconfig: 2345 50 30
# description: Kaspersky Anti-Virus server

# Basic support for the Linux Standard Base Specification 1.0.0 (to be used by
# insserv for exemple)
### BEGIN INIT INFO
# Provides: aveserver
# Required-Start: $network $syslog
# Required-Stop:
# Default-Start:
# Default-Stop:
# Description: Kaspersky Anti-Virus server
# Short-Description: Kaspersky Anti-Virus server
### END INIT INFO

AVESERVER_BIN=/usr/bin/aveserver
KAV_CONF=/etc/kav/kav4mailservers.conf

get_avpid() {
  if [ -s $KAV_CONF ]; then
      AVPID=`grep "^\s*AVSpidPATH=" $KAV_CONF | cut -d= -f2`
      if [ -n "$AVPID" -a -f "$AVPID" ] ; then
        PID=`head $AVPID 2>/dev/null`
	if [ -n "$PID" ] ; then
	    echo "$PID"
    	    return 0
	else
    	    echo "PID file is empty"
    	    return 1
	fi
      else
        echo "Can't find pid file $AVPID"
        return 1
      fi
    else
      echo "Config file not found"
      exit 1
  fi 
}

start() {
  if [ -x $AVESERVER_BIN ]; then
      $AVESERVER_BIN -c $KAV_CONF
      if [ $? -eq 0 ]; then
          echo "aveserver was started"
        else 
          echo "aveserver couldn't be started"
	  exit 1
      fi
    else 
      echo "$AVESERVER_BIN was not found"
      exit 2
  fi  
  
}

stopkav() {
  PID=`get_avpid`
  if [ $? -eq 0 ] ; then
    kill -TERM $PID 2> /dev/null
    if [ $? -eq 0 ]; then
        echo "aveserver was stopped"
        return 0
    fi
  fi
  echo "aveserver couldn't be stopped" 
  return 1
}

status() {
    pid=`get_avpid`
    rc=$?
    if [ $rc -eq 0 ] ; then
	kill -0 "$pid" 2>/dev/null
	if test $? -eq 0 ; then
	    status="running"
	    rc=0
	else
	    status="dead"
	    rc=1
	fi
    else
	status="stopped"
	rc=3
    fi
    echo "aveserver is $status"
    exit $rc
}

reload() {
  PID=`get_avpid`
  if [ $? -eq 0 ] ; then
    kill -HUP $PID 2> /dev/null
    if [ $? -eq 0 ]; then
        echo "aveserver was reloaded"
        return 0
    fi
  fi
  echo "aveserver couldn't be reloaded"
  exit 1
}

case $1 in 
	start)
		start
		;;
	stop)
		stopkav
		;;
	status)
		status
		;;
	restart)
		stopkav
		sleep 1
		start
		;;
	force-reload|reload)
		reload
		;;	
	*)
		echo "Usage: ${0##*/} {start|stop|restart|reload|status}"
		;;
esac

exit 0
