#!/bin/bash
#---
# Excerpted from "Raspberry Pi: A Quick-Start Guide, 2nd Edition",
# published by The Pragmatic Bookshelf.
# Copyrights apply to this code. It may not be used to create training material, 
# courses, books, articles, and the like. Contact us if you are in doubt.
# We make no guarantees that this code is fit for any purpose. 
# Visit http://www.pragmaticprogrammer.com/titles/msraspi2 for more book information.
#---

#!/bin/bash
green=18
yellow=23
red=24

init_leds() 
{
  for i in $green $yellow $red
  do
    gpio -g mode $i out
    gpio -g write $i 0
  done
}

set_led()
{
  led_status=`gpio -g read $1`
  if [ "$led_status" -ne 1 ]
  then
    init_leds
    gpio -g write $1 1
  fi
}

cleanup()
{
  init_leds
  exit 0
}

init_leds
trap cleanup INT TERM EXIT 

while :
do
  total=`free | grep Mem | tr -s ' ' | cut -d ' ' -f 2` 
  free=`free | grep Mem | tr -s ' ' | cut -d ' ' -f 4`
  available=$(( free * 100 / total )) 
  echo -n "$available% of memory available -> "

  if [ "$available" -le 10 ]
  then
    echo "Critical"
    set_led $red
  elif [ "$available" -le 30 ]
  then
    echo "Low"
    set_led $yellow
  else
    echo "OK"
    set_led $green
  fi
  sleep 10
done

