#! /bin/bash
# ---------------------------------------------------------------------------------
# Script to stop/start and give a status of our web service in the cluster.
# This script is build to receive 3 parameters.
#    - start :  Executed by cluster to start the application(s) or service(s)
#    - stop  :  Executed by cluster to stop  the application(s) or service(s) 
#    - status:  Executed by cluster every 30 seconds to check service status.
# ---------------------------------------------------------------------------------
# Author    : Jacques Duplessis - April 2011
# ---------------------------------------------------------------------------------
#set -x 
CDIR="/cadmin"              ; export CDIR       # Root directory for Services
CSVC="$CDIR/srv"            ; export CSVC       # Service Scripts Directory
CCFG="$CDIR/cfg"            ; export CCFG       # Service Config. Directory
INST="srv_www"              ; export INST       # Service Instance Name
LOG="$CDIR/log/${INST}.log" ; export LOG        # Service Log file name
HOSTNAME=`hostname -a`      ; export HOSTNAME   # HostName
HTTPD="/usr/sbin/httpd"     ; export HTTPD      # Service Program name
HCFG="${CCFG}/${INST}.conf" ; export HCFG       # Service Config. file name
RC=0                        ; export RC         # Service Return Code
DASH="---------------------"; export DASH       # Dash Line

# Where the Action Start
# ---------------------------------------------------------------------------------
case "$1" in 
  start)  echo -e "\n${DASH}" >> $LOG 2>&1
          echo -e "Starting service $INST on $HOSTNAME at `date`" >> $LOG 2>&1
          echo -e "${HTTPD} ${HCFG}" >> $LOG 2>&1
          ${HTTPD} -f ${HCFG} >> $LOG 2>&1
          RC=$?
          HPID=`cat ${CCFG}/${INST}.pid`
          echo "Service $INST started on $HOSTNAME - PID=${HPID} RC=$RC">> $LOG
          echo "${DASH}" >> $LOG 2>&1		
          ;;
  stop )  echo -e "\n${DASH}" >> $LOG 2>&1 
          echo -e "Stopping Service $INST on $HOSTNAME at `date` " >> $LOG
          HPID=`cat ${CCFG}/${INST}.pid`
          echo -e "Killing PID ${HPID}" >> $LOG 2>&1
          kill $HPID  > /dev/null 2>&1
          echo -e "Service $INST is stopped ..." >> $LOG 2>&1
          RC=0
          echo "${DASH}" >> $LOG 2>&1		
          ;;
  status) COUNT=`ps -ef | grep ${HCFG}| grep -v grep | wc -l` 
          HPID=`cat ${CCFG}/${INST}.pid`
          echo -n "`date` Service $INST ($COUNT) on $HOSTNAME">> $LOG 2>&1
          if [ $COUNT -gt 0 ] 
             then echo " - PID=${HPID} - OK"  >> $LOG 2>&1
                  RC=0
             else echo " - NOT RUNNING" >> $LOG 2>&1
                  ps -ef | grep -i ${HCFG} | grep -v grep  >> $LOG 2>&1
                  RC=1
          fi
          ;;
esac
exit $RC

