#A plugin for matching patterns.

version=0.1
author="Anto Aravinth"


#Exit codes usage.
ST_OK=0
ST_WR=1
ST_CR=2
ST_UK=3

print_help() {
	echo "Options:"
	echo "--help|-h)"
	echo "		Prints the help message"
	echo "--version|-v)"
	echo "		Prints the version details"
	echo "--filepath|-f)"
	echo "		Sets the path which need to monitored"
	echo "--regex|-r)"
	echo "		Sets the regex which will be used to match"
	echo "		the details with the file specified by path."
	echo "--warninglimit|-wl)"
	echo "		Sets the warning threshold"
	echo "--criticallimit|-cl)"
	echo "		Sets the critical threshold"
}

print_version(){
	echo $version
	echo $author
}

while test -n "$1"; do
    case "$1" in
        --help|-h)
            print_help
            exit $ST_UK
            ;;
        --version|-v)
            print_version $PROGNAME $VERSION
            exit $ST_UK
            ;;
        --filepath|-f)
            filepath=$2
	    shift
	    ;;
	--regex|-r)
	    regex=$2
	    shift
	    ;;
	--warninglimit|-wl)
	    warning=$2
            shift
            ;;
	--criticallimit|-cl)
	    critical=$2
   	    shift
            ;;       
        *)
            echo "Unknown argument: $1"
            print_help
            exit $ST_UK
            ;;
    esac
    shift
done


number=$(tail -n 500 $filepath | cut -f4 | grep $regex | wc -l;)

if [ ${number} -ge ${warning} -a ${number}  -lt ${critical} ]
        then
            echo "WARNING - there are ${warning} $regex errors in apache error logs!"
            exit $ST_WR
        elif [ ${number} -ge ${critical} ]
        then
            echo "CRITICAL - there are more than $critical $regex errors in apache error logs! There are $number of $regex errors"
        exit $ST_CR
        else
            echo "OK - everything seems to be ok :)"
            exit $ST_OK
        fi
    else
        echo "OK"
        exit $ST_OK
    fi


