#!/bin/sh

##
## This script is inspired by
## http://people.freebsd.org/~rse/dist/freebsd-memory
##

# Set default values
APPDIR=${APPDIR:-..}
VERBOSE=${VERBOSE:-0}

. ${APPDIR}/common.subr

#
# multiply_page value
# 	Multiplies value with the page size
#
multiply_page()
{
	local pagesize
	pagesize=`sysctl -n hw.pagesize 2>/dev/null`
	echo "$1 * $pagesize" | bc
}

#
# calc_mb bytes
#	Calculates the amount of megabytes from bytes
#
calc_mb()
{
	local mb
	mb=$(( 1024 * 1024 ))
	echo "$1 / $mb" | bc
}

physmem=`sysctl -n hw.physmem 2>/dev/null`
activemem=$(multiply_page `sysctl -n vm.stats.vm.v_active_count`)
inactmem=$(multiply_page `sysctl -n vm.stats.vm.v_inactive_count`)
cachemem=$(multiply_page `sysctl -n vm.stats.vm.v_cache_count`)
allmem=$(multiply_page `sysctl -n vm.stats.vm.v_page_count`)
wiremem=$(multiply_page `sysctl -n vm.stats.vm.v_wire_count`)
freemem=$(multiply_page `sysctl -n vm.stats.vm.v_free_count`)

availmem=$(($inactmem + $cachemem + $freemem))
usedmem=$(($physmem - $availmem))

sect "RAM information"

subsect "Memory information from dmidecode(8)"

if ! which -s dmidecode; then
	# Advice user to install it
	warn "You will need to install the sysutils/dmidecode port in order to obtain this information.\n"
else
if check_privs /dev/mem; then
	dmidecode -t memory | sed -En 's/^[[:space:]]+//; /Maximum|Number Of/p'
	echo
	info "Run \`dmidecode -t memory\` to see further information."
	echo
fi
fi

# this will be displayed only if verbose level is higher than 0
if is_verbose 1; then
	subsect "System memory information"

	cat <<EOF
Wired memory	- disabled for paging out	$(calc_mb $wiremem) MB
Active memory	- recently referenced		$(calc_mb $activemem) MB
Inactive memory	- recently not referenced	$(calc_mb $inactmem) MB
Cached memory	- almost avail. for allocation	$(calc_mb $cachemem) MB
Free memory	- fully avail. for allocation	$(calc_mb $freemem) MB

EOF

fi

subsect "System memory summary"

cat <<EOF
Total real memory available:	$(calc_mb $physmem) MB
Logically used memory:		$(calc_mb $usedmem) MB
Logically available memory:	$(calc_mb $availmem) MB

EOF

subsect "Swap information";
swapinfo -h

exit 0
