#!/bin/sh -e
#
#    mem_used: grab the current memory usage
#
#    Copyright (C) 2008 Canonical Ltd.
#    Copyright (C) 2011 Dustin Kirkland
#
#    Authors: Dustin Kirkland <kirkland@ubuntu.com>
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, version 3 of the License.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

__mem_used_detail() {
	cat /proc/meminfo
}

__mem_used() {
	# originally, this script did:
	# f=$(free | awk '/buffers\/cache:/ {printf "%.0f", 100*$3/($3 + $4)}')
	# this method is more dependent on /proc/meminfo, but uses the same formula
	# for deriving the output of 'free' that is used in procps 'free.c'
	# kb_main_free, kb_main_total, kb_main_buffers, kb_main_cached
	local free="" total="" buffers="" cached=""
	local kb_main_used=0 buffers_plus_cached=0 fo_buffers=0 fo_cached=0
	while read tok val unit; do
		case "$tok" in
			MemTotal:) total=${val};;
			MemFree:) free=${val};;
			Buffers:) buffers=${val};;
			Cached:) cached=${val};;
		esac
		[ -n "${free}" -a -n "${total}" -a -n "${buffers}" -a -n "${cached}" ] && break;
	done < /proc/meminfo
	kb_main_used=$(($total-$free))
	buffers_plus_cached=$(($buffers+$cached))
	# "free output" buffers and cache (output from 'free')
	fo_buffers=$(($kb_main_used - $buffers_plus_cached))
	fo_cached=$(($kb_main_free + $buffers_plus_cached))
	fpdiv $((100*${fo_buffers})) "${total}" 0;
	f=${_RET}
	color b g W; printf "%s" "$f"; color -; color g W; printf "%%"; color --
}

# vi: syntax=sh ts=4 noexpandtab
