#!/bin/bash
#Written by Scott Sullivan (ssullivan@liquidweb.com)
#
#This is an automated openfire service check script. This script
#will restart Openfire when it's down. Script runs every 30 seconds.

DATE=`date "+%m%d%y [%k:%M]"`
LOGDATE=`date "+%m-%d-%y [%k:%M:%S]"`
mail=/bin/mail
sysadmin=jordan@hall05.co.uk
openfirefile=/tmp/openfire.txt
logfile=/var/log/openfirecheck.log

echo "$LOGDATE - OpenFire Service Check starting up " >> $logfile

function stopopenfire
{
        /etc/init.d/openfire stop > /dev/null 2>&1
}

function startopenfire
{
        DATE=`date "+%m%d%y [%k:%M]"`
        LOGDATE=`date "+%m-%d-%y [%k:%M:%S]"`
        stopopenfire
        echo "OpenFire Service Down, attempting to restart on $DATE" >> $openfirefile
        cat $openfirefile | $mail -s 'OpenFire Restart' $sysadmin
        /etc/init.d/openfire stop > /dev/null 2>&1
        /etc/init.d/openfire start > /dev/null 2>&1
        rm $openfirefile
}

function checkpid
{
        DATE=`date "+%m%d%y [%k:%M]"`
        LOGDATE=`date "+%m-%d-%y [%k:%M:%S]"`
        # ps xua | grep -q openfire
        #/etc/init.d/openfire status | grep "openfire is running"
        /etc/init.d/openfire status | grep "openfire is running" > /dev/null 2>&1
        if [ $? != 0 ]
        then
                echo "$LOGDATE - No OpenFire Running! Restarting..." >> $logfile
                startopenfire
        else
                echo "$LOGDATE - OpenFire Running..." >> $logfile
        fi
}

count="0"
while [  $count -lt "10" ]; do
        checkpid
        sleep 30s
done

