#!/bin/sh
PATH="/bin:/usr/bin:/usr/sbin"
export PATH

USAGE="$0 [-v(verify)] [-b[brief] [-l(long listing)] [-h(help)]"

TMP=/tmp/showver_$$
VFILE=/opt/meru/etc/version

cleanup()
{
	[ "$TMP" ] && rm -f $TMP
}

fail()
{
	[ "$1" ] && echo "$1" 
	cleanup
	exit 1
}

help()
{
	echo "The showver command displays version information and verifies installed files."
	echo "The following options are accepted:"
	echo "    -b: Brief listing shows the overall product version."
	echo "    -h: Help. This menu".
	echo "    -l: Long listing shows the rpm header information for each package installed on the system."
	echo "    -v: Verify files installed on the system match the rpm database attributes."
	echo "Verify output:"
	echo "The format of the output is a string of 8 characters, a possible \"c\" denoting a configuration file, and"
	echo "then the file name. Each of the 8 characters denotes the result of a comparison of attribute(s) of the file"
	echo "to the value of those attribute(s) recorded in the database. A single \".\" (period) means the test passed,"
	echo "while  a single "?"  indicates the test could not be performed (e.g. file permissions prevent reading)."
	echo "Otherrwise, the (mnemonically emBoldened) character denotes failure of the corresponding verify test:"
	echo "S file Size differs"
	echo "M Mode differs (includes permissions and file type)"
	echo "5 MD5 sum differs"
	echo "D Device major/minor number mis-match"
	echo "L readLink(2) path mis-match"
	echo "U User ownership differs"
	echo "G Group ownership differs"
	echo "T mTime differs"
	echo
	cleanup
	exit 0
}

#
# main()
#
opts="lvbh"

getopt "$opts" $* >/dev/null 2>&1
if [ $? != 0 ]
then
	echo $USAGE
	exit 2
fi

set -- `getopt "$opts" $*`
for i in $*
do
	case $i in
	-v)	 VERIFY=true;	shift ;;
	-l)	 LONG=true;	shift ;;
	-b)	 BRIEF=true;	shift ;;
	-h)	 help		shift ;;
	--)	 		shift;	break ;;
	esac
done


[ "$BRIEF" ] && {
	if [ -f $VFILE ]; then
		cat $VFILE
	else
		fail "Cannot find $VFILE"
	fi
	cleanup
	exit 0
}


rpm -q -a | grep meru > $TMP
[ -s $TMP ] || {
	echo "No Meru packages installed"
	cleanup	
	exit 0
}


[ "$VERIFY" ] && {
	echo "The verify option may take several minues to complete. Run $0 -h for output semantics."

	for pkg in `cat $TMP`
	do
		echo "Checking for modified files in $pkg ..."
		rpm -V $pkg
	done
	cleanup
	exit 0
}


echo "Meru rpms installed:"
for pkg in `cat $TMP`
do
	if [ "$LONG" ]; then
		echo
		rpm -q -i $pkg
	else
		echo "    $pkg"
	fi
done

cleanup
exit 0
