#!/bin/sh
#
# Script to mimic the Linux utility 'free' on a Solaris machine.  Don't consider
# the numbers presented to be too accurate, but they should help diagnose system
# performance problems.  Requires swap, ps, and top.
#
# Written by:  Chris Studholme
# Last Update: 8-Jan-1999
# Copyright:   GPL (http://www.fsf.org/copyleft/gpl.html)
#

PS=`which ps`
SWAP=`which swap`
TOP=`which top`

# get swap info
set `$SWAP -l|grep -v "^swapfile"|awk '{t+=$4; f+=$5} END {print t/2,f/2,(t-f)/2}'`
swaptotal=$1
swapfree=$2
swapused=$3

# virtual memory info
set `$SWAP -s|tr -d "k"|awk '{print $2,$6,$9,$11,$9+$11}'`
virtalloc=$1
virtres=$2
virtused=$3
virtfree=$4
virttotal=$5
pstotal=`$PS -A -o vsz|grep -v VSZ|awk '{sum+=$1} END {print sum}'`
tmpused=`df -k /tmp|grep "^swap"|awk '{print $3}'`

# real memory info
set `$TOP -un 0|grep "^Memory:"|tr -d "K"|awk '{print $2,$4}'`
realtotal=$1
realfree=$2
if echo "$realtotal"|grep M>/dev/null; then
    realtotal=`echo "$realtotal"|tr -d "M"`
    realtotal=`expr "$realtotal" \* 1024`
fi
if echo "$realfree"|grep M>/dev/null; then
    realfree=`echo "$realfree"|tr -d "M"`
    realfree=`expr "$realfree" \* 1024`
fi
realused=`expr 0"$realtotal" - 0"$realfree"`

# calculations
buffers=`expr "$realused" + "$swapused" - "$virtused"`
if [ "$buffers" -lt 0 ]; then
	buffers=0
fi
procused=`expr "$realused" - "$buffers"`
procfree=`expr "$realfree" + "$buffers"`
shared=`expr "$pstotal" - "$virtused" + "$tmpused"`

# output report
printf "             total       used       free     shared    buffers        tmp\n"
printf "Mem:    %10s %10s %10s %10s %10s %10s\n" "$realtotal" "$realused" "$realfree" "$shared" "$buffers" "$tmpused"
printf "-/+ buffers:       %10s %10s\n" "$procused" "$procfree"
printf "Swap:   %10s %10s %10s\n" "$swaptotal" "$swapused" "$swapfree"
