Parse the last minutes of a log file

Script that returns how many times a certain string shows up in a log file in the last X minutes.

#!/bin/sh
# for FreeBSD
# returns how many times $STRING shows up in $LOGFILE
# in the last $MINUTES minutes
# if $LINES is passed to the script, only so many lines
# will be parsed
# assumes a time format like 'Feb 22 23:52:04'

LOGFILE=$1
STRING=$2
MINUTES=$3    # defaults to 60 minutes
LINES=$4      # if not passed, the whole file will be used

if [ -z "$LOGFILE" ] || [ -z "$STRING" ]; then
    # logfile and string are mandatory
    echo "1"
    exit 1
fi

if [ ! -f "$LOGFILE" ]; then
    # log file doesn't exist
    echo "1"
    exit 1
fi

if [ -z "$MINUTES" ]; then
    MINUTES="60"
fi

# get the lines to be parsed in a buffer
if [ -z "$LINES" ]; then
    LOGBUFF=`tail -n $LINES $LOGFILE`
else
    LOGBUFF=`cat $LOGFILE`
fi

NOW=`date +%s`
MINAGO=$(( $NOW - 60 * $MINUTES ))

# check if the string is present anywhere
# if it isn't there's no point in continuing
LNCOUNT=`echo "$LOGBUFF" | grep -c $STRING` # echo "$a" keeps newlines
if [ "$LNCOUNT" == 0 ]; then
    echo "0"
    exit 0
fi

# string is in the buffer, so check if it's in last $MINUTES
COUNT=`echo "$LOGBUFF" | awk -v now=$NOW -v minago=$MINAGO -v string=$STRING -v count=0 '
    {
        logdate=substr($0,1,15)
        "date -j -f \"%b %d %T\" \"" logdate "\" +%s" | getline logepoch
        if (logepoch > minago && logepoch < now && index($0,string) > 0)
            count++
    }
    END { print count }'`

echo $COUNT
exit $COUNT