#!/bin/bash

# Copyright (c) 2009 Tao Effect LLC
# 
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
# 
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.

if [[ -n "$1" && "$1" = "-h" ]] ; then
	echo "Usage:"
	echo "	Top 10:  ./memusage"
	echo "	Top num: ./memusage [num]"
	echo "	Find:    ./memusage [process name]"
	echo ""
	echo "Author: Greg Slepak"
	return 0
fi
	

printspaces() {
	numspaces=$(( 24 - $1 ))
	for (( k = 0; k < $numspaces; k++ )) ; do
		echo -n " "
	done
}

top() {
	echo "Top $1 memory intensive apps:"
	echo ""
	array=( `ps auwwxm | awk '{ print $11, $4, $6 / 1024 }'` )
	count=1
	echo "	Name			Percentage	Size"
	echo ""
	for (( i = 3; i <= $1*3; i+=3 )) ; do
		name=`expr "${array[$i]}" : '.*/\(.*\)'`
		len=${#name}
		echo -n "#$count:	$name"
		printspaces $len
		echo "${array[$((i+1))]}		${array[$((i+2))]} MB"
		count=$(( count+1 ))
	done
}

if [[ -z "$1" ]] ; then	
	top 10
else
	# find out if $1 is a number
	# trick from: http://www.linuxforums.org/forum/linux-programming-scripting/66150-how-make-system-only-accept-numbers.html
	try=$1
	try=$[try+0]
	if [ $1 = $try ] ; then
		top $1
	else
		RES=`ps auwwx | grep -i $1 | grep -v "\(memusage\|grep\)"`
		if [ -n "$RES" ] ; then
			name=`echo $RES | awk '{ print $11 }'`
			name=`expr "$name" : '.*/\(.*\)'`
			specs=`echo $RES | awk '{ print $4, "% ", $6 / 1024 , "MB" }'`
			echo "$name: $specs"
		fi
	fi 
fi

