#!/bin/sh
#
# Log file pattern detector plugin for Nagios
# Written by Ethan Galstad (nagios@nagios.org)
# Modified by Florian Gleixner
# Last Modified: 02-25-2004
#
# Usage: ./check_log -F <log_file> -O <state_file> -q <pattern>
#
# Description:
#
# This plugin will scan a log file (specified by the <log_file> option)
# for a specific pattern (specified by the <pattern> option).  Successive
# calls to the plugin script will only report *new* pattern matches in the
# log file, since the size of the log file from the previous run is saved
# to <state_file>.
#
# Output:
#
# On the first run of the plugin, it will return an OK state with a message
# of "Log check data initialized".  On successive runs, it will return an OK
# state if *no* pattern matches have been found in the lines added between the
# log file and the last run.  If the plugin detects any 
# pattern matches in the log lines added, it will return a CRITICAL state and print
# out a message is the following format: "(x) last_match", where "x" is the
# total number of pattern matches found in the file and "last_match" is the
# last entry in the log file which matches the pattern.
#
# Notes:
#
# If you use this plugin make sure to keep the following in mind:
#
#    1.  The "max_attempts" value for the service should be 1, as this
#        will prevent Nagios from retrying the service check (the
#        next time the check is run it will not produce the same results).
#
#    2.  The "notify_recovery" value for the service should be 0, so that
#        Nagios does not notify you of "recoveries" for the check.  Since
#        pattern matches in the log file will only be reported once and not
#        the next time, there will always be "recoveries" for the service, even
#        though recoveries really don't apply to this type of check.
#
# Examples:
#
# Check for login failures in the syslog...
#
#   check_log /var/log/messages ./check_log.badlogins.old "LOGIN FAILURE"
#
# Check for port scan alerts generated by Psionic's PortSentry software...
#
#   check_log /var/log/message ./check_log.portscan.old "attackalert"
#

# Paths to commands used in this script.  These
# may have to be modified to match your system setup.

PATH=""

ECHO="/bin/echo"
GREP="/bin/grep"
DIFF="/bin/diff"
TAIL="/usr/bin/tail"
CAT="/bin/cat"
RM="/bin/rm"
AWK="/bin/awk"
SED="/bin/sed"
LS="/bin/ls"
BC="/usr/bin/bc"

#find uname
if [ -x "/bin/uname" ] ; then 
  OS=`/bin/uname`
elif [ -x "/usr/bin/uname" ] ; then
  OS=`/usr/bin/uname`
else
  OS="Unknown"
fi

case "$OS" in 
	"SunOS")
	  TAIL="/usr/xpg4/bin/tail"
	  AWK="/usr/bin/nawk"
	  GREP="/usr/bin/egrep"
          SED="/usr/bin/sed"
	  ECHO="/usr/bin/echo"
	  DIFF="/usr/bin/diff"
	  CAT="/usr/bin/cat"
	  RM="/usr/bin/rm"
	  LS="/usr/bin/ls"
	  ;;
esac

PROGNAME=`/bin/basename $0`
PROGPATH=`echo $0 | /bin/sed -e 's,[\\/][^\\/][^\\/]*$,,'`
REVISION=`echo '$Revision: 1.4 $' | /bin/sed -e 's/[^0-9.]//g'`

. $PROGPATH/utils.sh

print_usage() {
    echo "Usage: $PROGNAME -F logfile -S statefile [-q query | -e extendedquery]"
    echo "Usage: Old Syntax:"
    echo "Usage: $PROGNAME -F logfile -O statefile -q query"
    echo "Usage: $PROGNAME --help"
    echo "Usage: $PROGNAME --version"
}

print_help() {
    print_revision $PROGNAME $REVISION
    echo ""
    print_usage
    echo ""
    echo "Log file pattern detector plugin for Nagios"
    echo ""
    support
}


write_statefile() {
	newsize=`$LS -Ll $logfile | $AWK '{print $5}' `
	if [ -f "$oldlog" ] ; then
		oldsize=`$CAT $oldlog`
	fi
	echo $newsize > $oldlog
}

# Make sure the correct number of command line
# arguments have been supplied

if [ $# -lt 1 ]; then
    print_usage
    exit $STATE_UNKNOWN
fi

# Grab the command line arguments

#logfile=$1
#oldlog=$2
#query=$3
exitstatus=$STATE_WARNING #default
while test -n "$1"; do
    case "$1" in
        --help)
            print_help
            exit $STATE_OK
            ;;
        -h)
            print_help
            exit $STATE_OK
            ;;
        --version)
            print_revision $PROGNAME $VERSION
            exit $STATE_OK
            ;;
        -V)
            print_revision $PROGNAME $VERSION
            exit $STATE_OK
            ;;
        --filename)
            logfile=$2
            shift
            ;;
        -F)
            logfile=$2
            shift
            ;;
	--statefile)
	    oldlog=$2
	    shift
	    ;;
	-S)
	    oldlog=$2
	    shift
	    ;;
        --oldlog)
            oldlog=$2
            shift
            ;;
        -O)
            oldlog=$2
            shift
            ;;
        --query)
            query=$2
            shift
            ;;
        -q)
            query=$2
            shift
            ;;
	-e)
	    query="-e $2"
	    shift
	    ;;
	--extendedquery)
	    query="-e $2"
	    shift
	    ;;
        -x)
            exitstatus=$2
            shift
            ;;
        --exitstatus)
            exitstatus=$2
            shift
            ;;
        *)
            echo "Unknown argument: $1"
            print_usage
            exit $STATE_UNKNOWN
            ;;
    esac
    shift
done

# If the source log file doesn't exist, exit

if [ ! -e $logfile ]; then
    $ECHO "Log check error: Log file $logfile does not exist!\n"
    exit $STATE_UNKNOWN
fi

# If statefile is not given, use a file in /tmp

if [ -z "$oldlog" ] ; then
        oldlog="/tmp/nagios_state"`$ECHO $logfile | $SED 's/\//_/g' -`
fi

# If the statefile doesn't exist, this must be the first time
# we're running this test, so wrie the size in

if [ ! -e $oldlog ]; then
    write_statefile
    $ECHO "Log check data initialized...\n"
    exit $STATE_OK
fi

# The state file exists, so compare size to the original log now

#this writes the new size and gets the old and new sizes in
#$oldsize and $newsize
write_statefile

# the bash can calculate much more better than the shell.
# there we could have diffsize=$((newsize-oldsize))
diffsize=`$ECHO "$newsize-$oldsize\n" |$BC` 
if [ "$diffsize" -gt 0 ] ; then


  # Count the number of matching log entries we have
  count=`$TAIL -c $diffsize $logfile | $GREP -c "$query"`

  # Get the last matching entry in the diff file
  lastentry=`$TAIL -c $diffsize $logfile | $GREP "$query"|$TAIL --lines=1`


  if [ "$count" = "0" ]; then # no matches, exit with no error
      $ECHO "Log check ok - 0 pattern matches found\n"
      exitstatus=$STATE_OK
  else # Print total matche count and the last entry we found
      $ECHO "($count) $lastentry"
      exitstatus=$STATE_CRITICAL
  fi
else
  $ECHO "Log check ok - File unchanged\n"
  exitstatus=$STATE_OK
fi

exit $exitstatus
