#!/bin/bash
#
# ::copy::
# ::maintainer::

CMD=`basename $0`


# (FUNCTIONS)

usage()
{
	echo "
usage: $CMD [options] [system(s)..]

options:
  -h|--no-header	don't show top header
  -x|--xen-list		show xm list only

" >&2
	exit 1
}

# (MAIN)

# parse args
#
f_header=true
f_xenlist=false
systems=

while [ $# != 0 ]
do
  case $1 in
    -v|--verbose)	VERBOSE=true ;;
    -q|--quiet)		VERBOSE=false ;;
    -D|--debug)		DEBUG=true ;;
    -h|--no-header)	f_header=false ;;
    -x|--xen-list)	f_xenlist=true ;;
    --)			shift ; break ;;
    -*|"")		usage ;;
    *)			systems="$systems $1" ;;
  esac
  shift
done
systems=`echo $systems $*`


fmt=" %-14.14s %-6.6s %-2.2s %-32.32s %-16.16s %-32.32s\n"
fmt_xen=" %-14.14s %-60.60s\n"
line="-----------------------------------------------------------------------------------"

$f_header && {
	if $f_xenlist
	then
		printf "$fmt_xen" "system" "vms list"
		printf "$fmt_xen" "$line" "$line"
	else
		printf "$fmt" "system" "rel" "ku" "kernel" "updated" "users"
		printf "$fmt" "$line" "$line" "$line" "$line" "$line" "$line"
	fi
}

for sys in $systems
do
	[ -d $sys ] || continue

	if $f_xenlist
	then
		if [ -f $sys/xmlist ]
		then
			xmlist=`cat $sys/xmlist`
			xmlist=`echo $xmlist`
		elif [ -f $sys/vmlist ]
		then
			xmlist=`sed -e '1,2d' $sys/vmlist | awk '{ print $2 }'`
			xmlist=`echo $xmlist`
		fi

		printf "$fmt_xen" "$sys" "$xmlist"
	else
		release=`[ -f $sys/release ] && cat $sys/release`
		kernel=`[ -f $sys/kernel ] && cat $sys/kernel`
		updated=`[ -f $sys/updated ] && cat $sys/updated`
		users=`[ -f $sys/users ] && cat $sys/users`
		users=`echo $users`
		[ `echo "$users" | wc -c` -gt 32 ] && {
			users=`echo "$users" | sed -e 's/^\(.......................\).*/\1 .../'`
		}
		ok=""
		[ -f $sys/kusa.conf ] 		&& ok="${ok}k"	|| ok="${ok} "

		printf "$fmt" "$sys" "$release" "$ok" "$kernel" "$updated" "$users"
	fi
done

exit 0
