#! /bin/bash

###################################################
# SCRIPT BASEADO NO COMANDO SAR DO PACOTE SYSSTAT #
# ANTES DE EXECUTA-LO INSTALE O SYSSTAT ###########
# apt-get install sysstat #########################
# yum -y install sysstat ##########################
# SCRIPT SHELL DESENVOLVIDO POR ERISSON CORREIA ###
# E-MAIL: erissonsilva@gmail.com ##################
###################################################

export LANG=en_US

SARCMD=$(which sar)
AWK=$(which awk)

pgpgin='$2'
pgpgout='$3'
fault='$4'
majflt='$5'
pgfree='$6'
pgscank='$7'
pgscand='$8'
pgsteal='$9'
invertfilter=""
AVGREAD=""

[ ! -x $SARCMD ] && echo -e "sysstat and sar are not installed.\n\n\tInstall sysstat package first." && exit 0

_usage(){
 echo -e "USAGE: $(basename ${0}) -w warn -c crit -f filtercolumn\n
\t-f filtercolumn:
\t\tpgpgin
\t\tpgpgout
\t\tfault
\t\tmajflt
\t\tpgfree - inverted filter
\t\tpgscank
\t\tpgscand
\t\tpgsteal"
}

_try_invertfilter(){
if [[ $invertfilter == "1" ]];
then	OPER1='>'
	OPER2='<='
	OPER3='>'
	OPER4='<=';
else
	OPER1='<'
	OPER2='>='
	OPER3='<'
	OPER4='>=';
fi
}

_fncheck(){
_try_invertfilter

COMPARE=$(echo $AVGREAD $OPER1 $WARN|bc);
COMPARE2=$(echo $AVGREAD $OPER2 $WARN|bc);
COMPARE3=$(echo $AVGREAD $OPER3 $CRIT|bc);
COMPARE4=$(echo $AVGREAD $OPER4 $CRIT|bc);

OUTPUT="Memory $FILTER is $AVGREAD average/s.|AVGREAD=$AVGREAD;WARN=$WARN;CRIT=$CRIT"

if [[ $COMPARE == "1" && $COMPARE3 == "1" ]];
then
	STATE=0;
	echo "OK. $OUTPUT" 
fi
if [[ $COMPARE2 == "1" && $COMPARE3 == "1" ]];
then
	STATE=1;
	echo "WARNING. $OUTPUT"
fi
if [[ $COMPARE4 == "1" ]];
then
	STATE=2;
	echo "CRITICAL. $OUTPUT"
fi
return $STATE
}

while getopts ":w:c:f:h" opcao
do
case $opcao in
	w) WARN=$OPTARG;;
	c) CRIT=$OPTARG;;
	f) SARCOLMN=$OPTARG;;
	h) _usage && exit 0;;
	\?) _usage && exit 0;;
esac
done
#echo chegou aqui
#echo $($SARCMD -B 1 10|tail -n 1)
#echo chegou aqui
case $SARCOLMN in
	pgpgin) AVGREAD=`$SARCMD -B 1 10| tail -n 1|$AWK '{print \$2}'` && FILTER="pgpgin";
	;;
	pgpgout) AVGREAD=`$SARCMD -B 1 10| tail -n 1|$AWK '{print \$3}'` && FILTER="pgpgout";
	;;
	fault) AVGREAD=`$SARCMD -B 1 10| tail -n 1|$AWK '{print \$4}'` && FILTER="fault";
	;;
	majflt) AVGREAD=`$SARCMD -B 1 10| tail -n 1|$AWK '{print \$5}'` && FILTER="majflt";
	;;
	pgfree) AVGREAD=`$SARCMD -B 1 10| tail -n 1|$AWK '{print \$6}'` && FILTER="pgfree" && invertfilter=1;
	;;
	pgscank) AVGREAD=`$SARCMD -B 1 10| tail -n 1|$AWK '{print \$7}'` && FILTER="pgscank";
	;;
	pgscand) AVGREAD=`$SARCMD -B 1 10| tail -n 1|$AWK '{print \$8}'` && FILTER="pgscand";
	;;
	pgsteal) AVGREAD=`$SARCMD -B 1 10| tail -n 1|$AWK '{print \$9}'` && FILTER="pgsteal";
	;;
	*) _usage && exit 0;
	;;
esac

_fncheck
