#!/bin/bash
#
# chkconfig: 2345 90 12
# description: Mail Washer Enterprise Server
#

# Variables
DAEMON=/opt/mwes/mwes.run
NAME=mwes
DESC="Mailwasher Enterprise Server"
PID=/var/run/mwes/mwes.pid


start() {

  # check to see if it running
  is_running
  IS_RUNNING=$?

  if [ $IS_RUNNING == 0 ]
    then
      echo -n "Starting $DESC: "
       $DAEMON start
       sleep 3
      echo "done"
    else
      echo "$DESC is already running"
  fi
}

stop() {

  # check to see if it running
  is_running
  IS_RUNNING=$?

  if [ $IS_RUNNING == 1 ]
    then
      echo -n "Stopping $DESC: "
      $DAEMON stop
      sleep 3
      echo "done"
    else 
      echo "$DESC is not running"
      if [ -f $PID ]
        then
          rm $PID
      fi
  fi
}


status() {

  is_running
  IS_RUNNING=$?

  if [ $IS_RUNNING == 0 ]
    then 
      echo "$DESC is NOT running"
    else 
      echo "$DESC is running"
  fi
}


is_running(){

  # check to see if the PID file exists
  if [ -f $PID ]
    then
      # get the contents of the PID file
      PID_NUM=$(cat $PID)
      SEARCH=$(ps --pid $PID_NUM -o comm=)
      #if we have a match between the PID in the file and the PID in the ps list ..
      if [ $SEARCH ]
        then
           return 1
        else
           return 0
      fi

    else
      # we have nothing
      return 0
      echo "$DESC is not running"
  fi
}


case "$1" in
  start)
        start
        ;;
  stop)
        stop
        ;;
  status)
        status
        ;;
  restart|reload|condrestart)
        stop
        start
        ;;
  *)
        echo $"Usage: $0 {start|stop|restart|reload|status}"
        exit 1
esac

exit 0
