#! /bin/bash
limitGB="6";
if [ ! -z "$1" ]
then
	limitGB=$1;
fi
freepages=$(vm_stat | grep free | awk '{print $3}' | tr -d . );
inactivepages=$(vm_stat | grep inactive | awk '{print $3}' | tr -d . );
speculativepages=$(vm_stat | grep speculative | awk '{print $3}' | tr -d . );
freeMB=$(($freepages * 4 / 1024 ));
inactiveMB=$(($inactivepages * 4 / 1024 ));
speculativeMB=$(($speculativepages * 4 / 1024 ));
unusedMB=$(($freeMB + $inactiveMB + $speculativeMB ));
unusedGB=$(awk -v var1=$unusedMB -v var2=1024 'BEGIN { printf "%.2f",  ( var1 / var2 ) }');
unusedGBr=$(awk -v var1=$unusedMB -v var2=1024 'BEGIN { printf "%.0f",  ( var1 / var2 ) }');
mostMemName=$(ps x -o pmem,comm | grep / | sort -r | head -n 1 | rev | cut -d/ -f1 | rev);
mostMemProz=$(ps x -o pmem,comm | grep / | sort -r | head -n 1 | awk '{print $1}');
secMemName=$(ps x -o pmem,comm | grep / | sort -r | head -n 2 | sort | head -n 1 | rev | cut -d/ -f1 | rev);
secMemProz=$(ps x -o pmem,comm | grep / | sort -r | head -n 2 | sort | head -n 1 | awk '{print $1}');
state="Free Ram : $unusedGB GB, gerundet: $unusedGBr GB, Limit: $limitGB GB, $mostMemName: $mostMemProz%, $secMemName: $secMemProz%";
jetzt=$(date '+%H:%M:%S');
echo "$jetzt: $state";
if [ -d "/Volumes/RamDisk/RamCheck" ]
then
	echo "$jetzt: $state" >> /Volumes/RamDisk/RamCheck/RamCheck.txt;
fi
#
if [ $unusedGBr -le $limitGB ]
then
	msg="Ram-Alarm $unusedGB ist kleiner als $limitGB";
	echo "$msg";
	osascript -e 'display alert "Ram-Alarm: Ram kleiner als Limit: $msg"';
fi