#!/bin/sh -
PATH=/usr/local/unixstat/bin:$PATH; export PATH

# stats - print requested single distribution statistics
# Steve Kinzler, steve@kinzler.com, Nov 93/Oct 09/Apr 23
# https://kinzler.com/me/home.html#unix

short=; bad=

while :
do
	case $# in
	0)	break;;
	*)	case "$1" in
		-s)	short=$1;;

		--)	shift; break;;
		-h)	bad=t; break;;
		-*)	bad=t; echo "$0: unknown option ($1)" 1>&2;;
		*)	break;;
		esac
		shift;;
	esac
done

case "$bad" in
?*)	cat << EOF 1>&2
usage: $0 [ -s ] [ key ... ]
	-s	short form output, print values only
EOF
	exit 1;;
esac

case $# in
0)	case "$short" in
	?*)	desc -v | sed 's/.*= *//';;
	*)	exec desc -v;;
	esac;;

1)	# let's handle the single special case of `stats sum`
	# with perl instead, for better decimal resolution and portability
	case "$1" in
	sum)	#if desc < /dev/null 2>&1 | grep -s data > /dev/null
		#then
		#	true
		#else
			perl -e 'for (<>) { $n += $_ }
				 print "'$short'" ? "" : "sum = ", $n+0, "\n"'
			exit;;
		#fi;;
	esac

	case "$short" in
	?*)	desc -v | sed -n "s/^$1 *= *//p";;
	*)	desc -v | grep "^$1 *=";;
	esac;;

*)	tmp=/tmp/stats$$
	trap "rm -f $tmp; exit" 0 1 2 13 15

	desc -v > $tmp

	for arg
	do
		case "$short$arg" in
		-s*)	sed -n "s/^$arg *= *//p" $tmp;;
		*)	grep "^$arg *=" $tmp;;
		esac
	done
esac
