#!/bin/bash
. /etc/7dtd.conf

if [[ "$MEM_NOTIFY_XMPP" = "no" ]]; then
	if [[ "$MEM_NOTIFY_MAIL" = "no" ]]; then
		exit
	fi
fi

PID=`$PIDOF 7DaysToDie.exe`

if [[ -z "$PID" ]]; then
	exit 0
fi

USED_CUR_MB=`$FREE -m | $AWK '/buffers\/cache/{print $3;}'`
#USED_CUR_MB=`cat /proc/$PID/status | $AWK '/VmRSS/{print int($2/1024);}'`
TELNETPORT=$(($SDTD_PORT + 3))
#USED_CHUNKS=`echo -e "cc" | nc -q 3 127.0.0.1 $TELNETPORT | grep -a Mem | awk '/Chunk/{print $3;}'`

if [ "$USED_CUR_MB" -gt "$MEM_NOTIFY_MAX_RAM" ]
then
	MESSAGE="7dtd: $USED_CUR_MB MiB of memory used! Chunk memory: $USED_CHUNKS"
	if [[ "$MEM_NOTIFY_XMPP" = "yes" ]]; then
		echo $MESSAGE | sendxmpp -u $XMPP_USER -p $XMPP_PASSWORD -j $XMPP_SERVER -t $XMPP_TARGET
	fi
	if [[ "$MEM_NOTIFY_MAIL" = "yes" ]]; then
		if [[ -n "$MAIL_USER" ]]; then
			userparam="-xu $MAIL_USER"
		fi
		if [[ -n "$MAIL_PASS" ]]; then
			passparam="-xp $MAIL_PASS"
		fi
		sendEmail -q -f $MAIL_FROM -t $MAIL_TO -u "$MAIL_SUBJECT" -m "$MESSAGE" -s $MAIL_SMTP $userparam $passparam
	fi
fi
