#!/bin/bash

# Nagios wrapper for poem_sync synchronizer

LAST_LOG_FILE='/var/log/poem/poem_last_run.log'

cmd_timeout() {
  sleep_time=$1  ; shift
  command=$@

  $command &
  cmd_pid=$!

  # sleep for our timeout then kill the process if it is running
  ( sleep $sleep_time && kill $cmd_pid && echo "ERROR - killed $command due to timeout $sleep_time exceeded" ) &
  killer_pid=$!
  
  # 'wait' for cmd_pid to complete normally.  If it does before the timeout is reached, then
  # the status will be zero.  If the killer_pid terminates it, then it will have a non-zero 
  # exit status
  wait $cmd_pid &> /dev/null
  wait_status=$?
  
  eval 'kill $killer_pid &> /dev/null' 2>&1 > /dev/null

  return $wait_status
}

STATE_OK=0
STATE_WARNING=1
STATE_CRITICAL=2
STATE_UNKNOWN=3
STATE_DEPENDENT=4

# Default Timeout
TIMEOUT=200

usage()
{
   cat <<EOF
usage: $0  [ -t timeout ] [ -v ] [ -h ]
   
Runs the POEM_SYNC syncronizer

OPTIONS:
    -t Specify a timeout, default $TIMEOUT
    -h Show this help
    -v Be verbose
EOF
}

while getopts "ht:v" OPTION
do
  case $OPTION in
     h)
      usage 
      exit $STATE_UNKNOWN
      ;;
     t)
       TIMEOUT=${OPTARG}
      ;;
     v)
       VERBOSE=1
      ;;
     ?)  
       exit $STATE_UNKNOWN
      ;;
     esac
done

if [ ! -e  $LAST_LOG_FILE ] 
then
	echo "Cannot find the Last Log file"
	echo "Please check the redirection in CRON job"
        exit $STATE_UNKNOWN
fi

if [ ! -s $LAST_LOG_FILE ] 
then
	### Zero file size indicates succesfull run
	echo "POEM_SYNC: poem_sync was succesfully run"
        exit $STATE_OK
fi

if [ `grep -q -- '- ERROR -' $LAST_LOG_FILE` ]
then 
	#### Last run has no error
	if [ ! `grep -q -- '- WARNING -' $LAST_LOG_FILE` ] 
	then
		### las run has warning
        cat $LAST_LOG_FILE
		echo "POEM_SYNC: Warning in running poem_sync, see logfile."
		exit $STATE_WARNING
	fi
	echo "POEM_SYNC: poem_sync was succesfully run"
	exit $STATE_OK
else 
	#### Last run has  error
	cat $LAST_LOG_FILE
	echo "POEM_SYNC: Error in running poem_sync, see logfile."
	exit $STATE_CRITICAL
fi
