#!/bin/bash


SWAP=1

function usage() {
	echo "Usage : $0 -w WARN_MEM,WARN_SWAP -c CRIT_MEM,CRIT_SWAP"
	echo "Seuil exprime en %"
	exit 1
}

[ $# -lt 4 -o "$1" == "-h" ] && usage
[ "$1" != "-w" -o "$3" != "-c" ] && usage

DEBUG=0
[ "$5" == "-d" ] && DEBUG=1

WM=`echo $2|cut -d',' -f1`
WS=`echo $2|cut -d',' -f2`
CM=`echo $4|cut -d',' -f1`
CS=`echo $4|cut -d',' -f2`

[ "$WM" == "" -o "$WS" == "" -o "$CM" == "" -o "$CS" == "" ] && usage

RET=0
MSG=""

MT=`free|grep Mem|awk '{print $2}'`
MU=`free|grep Mem|awk '{print $3-$7}'`
if [ "$MT" == "0" -o "$MT" == "" ]
then
	echo "CRITICAL - Can't read memory informations"
	exit 2
fi
let MR=MU*100/MT

if [ $MR -gt $CM ]
then
	RET=2
elif [ $MR -gt $WM ]
then
	RET=1
fi
MSG="Mem : $MR% used"
[ $DEBUG -eq 1 ] && echo "Mem : $MU / $MT => $MR%"

if [ $SWAP -eq 1 ]
then
	ST=`free|grep Swap|awk '{print $2}'`
	SU=`free|grep Swap|awk '{print $3}'`
	if [ "$ST" == "0" -o "$ST" == "" ]
	then
	        echo "CRITICAL - Can't read memory informations"
	        exit 2
	fi
	let SR=SU*100/ST

	if [ $SR -gt $CS ]
	then
	        RET=2
	elif [ $SR -gt $WS ]
	then
		[ $RET -eq 0 ] && RET=1
	fi
	MSG="$MSG - Swap : $SR% used"
	[ $DEBUG -eq 1 ] && echo "Swap : $SU / $ST => $SR%"
fi

[ $RET -eq 2 ] && echo "CRITICAL - $MSG" && exit 2
[ $RET -eq 1 ] && echo "WARNING - $MSG" && exit 1
echo "OK - $MSG"
exit 0
