#!/bin/bash

#
# make sure we use gawk
#

if [ -x /bin/gawk ]; then
    AWK="/bin/gawk"
elif [ -x /usr/bin/gawk ]; then
        AWK="/usr/bin/gawk"
else
    AWK="/usr/local/bin/gawk"
fi

# allow ctrl-C clean exit
trap 'exit 1' SIGINT

check_local_platform() {
	local_kernel_string=`cat /proc/version`
	local_kernel_sum=`echo $local_kernel_string | sum | cut -d' ' -f1`
	
	local_os_string=`cat /etc/*-release 2>/dev/null`
	# handle non-existance of release file
	if [ -n "$local_os_string" ]; then
		local_os_sum=`echo $local_os_string | sum | cut -d' ' -f1`
	else
		log info "skipping OS version checks (no '/etc/<name>-release' file)"
	fi
}

check_local_libraries() {
	local libs=`find /usr/lib -type f -name lib\*- 2>&1`

	if [ -n "$libs" ]; then
		log fail "libraries with names than can mask other libraries detected ($libs)"
	else
		log pass "no libraries with a masking name detected"
	fi
}

check_local_group() {
	# group checking
	group_line=`getent group rms 2>&1`
	rc=$?
	
	if [ $rc -ne 0 ]; then
		if [ $rc -eq 2 ]; then
			log fail "group 'rms' undefined"
			group_exists="no"
			return 1
		else
			log fail "error resolving group 'rms' ($group_line)"
			return 1
		fi
	else
		# store other information
		local_group_members=`echo $group_line | cut -d: -f4`
		group_gid=`echo $group_line | cut -d: -f3`
		
		if [ -n "$remote_gid" ]; then
			if [ "$remote_gid" != "$group_gid" ]; then
				log fail "group 'rms' has different gid than on rmshost (local $group_gid, rmshost $remote_gid)"
			else
				log pass "group 'rms' has same gid as on rmshost ($group_gid)"
			fi
		else
			log pass "group 'rms' defined (gid $group_gid, members '$local_group_members')"
		fi
	fi

	# success
	return 0
}

check_local_user() {
	# user checking
	user_line=`getent passwd $user 2>&1`
	rc=$?
	
	if [ $rc -ne 0 ]; then
		if [ $rc -eq 2 ]; then
			log fail "user '$user' undefined"
			
			user_exists="no"
			return 1
		else
			log fail "error resolving user '$user' ($user_line)"
			return 1
		fi
	else
		user_uid=`echo $user_line | cut -d: -f3`
		user_prigrp=`echo $user_line | cut -d: -f4`

		if [ -n "$remote_uid" ]; then
			if [ "$remote_uid" != "$user_uid" ]; then
				log fail "user '$user' has different uid than on rmshost (local $user_uid, rmshost $remote_uid)"
			else
				log pass "user '$user' has same uid as rmshost ($user_uid)"
			fi
		else
			log pass "user '$user' defined (uid $user_uid, gid $user_prigrp)"
		fi
	fi

	# test for being root, to avoid getting prompted for password
	if [ `id -nu` = "root" ]; then
		output=`su -s /bin/bash - $user -c hostname 2>&1`
		rc=$?
		if [ $rc -eq 0 ]; then
			log pass "commands can run as '$user'"
		else
			log fail "commands fail to run as '$user' ($output)"
		fi
	else
		log info "need to be root to test running commands as '$user'"
	fi

	# success
	return 0
}

check_local_membership() {
	id -Gn root | grep rms 2>&1 >/dev/null
	rc_rms=$?
	
	if [ $rc_rms -eq 0 ]; then
		log pass "user 'root' is a member of group 'rms'"
	else
		log fail "user 'root' is not a member of group 'rms'"
	fi
	
	id -Gn rms | grep rms 2>&1 >/dev/null
	rc_root=$?
	
	if [ $rc_root -eq 0 ]; then
		log pass "user 'rms' is a member of group 'rms'"
	else
		log fail "user 'rms' is not a member of group 'rms'"
	fi

	# return 1 if either test fails
	if [[ ("$rc_rms" -eq 1) || ("$rc_root" -eq 1) ]]; then
		return 1
	fi
	
	return 0
}

check_local_hosts() {
	rmshost_line=`getent hosts rmshost-primary`
	rc=$?

	# if 'rmshost-primary' not found, fall back to 'rmshost'
	if [ $rc -eq 2 ]; then
		rmshost_line=`getent hosts rmshost`
		rc=$?
	fi

	# test the return status
	if [ $rc -ne 0 ]; then
		if [ $rc -eq 2 ]; then
			log fail "host 'rmshost' undefined"
			return 1
		else
			log fail "error resolving host 'rmshost' ($rmshost_line)"
			return 1
		fi
	else
		rmshost=`echo $rmshost_line | $AWK '{print $2}'`
		rmshost_addr=`echo $rmshost_line | $AWK '{print $1}'`
		log pass "host 'rmshost' defined ($rmshost)"
	fi

	# note rmshost locality
	if [ "$hostname" == "$rmshost" ]; then
		rmshost_local="y"
	fi
	
	# check for localhost definition
	echo $rmshost_line | grep 127.0.0.1 >/dev/null
	rc=$?
	
	if [ $rc -eq 0 ]; then
		log fail "'rmshost' misdefined as localhost alias ($rmshost_line)"
		return 1
	fi
	
	# success
	return 0
}

check_local_packages() {
	# prepare list of common package versions
	package_get_versions $packages_common

	# allow skipping expensive package verification
	if [ -z "$no_check_packages" ]; then
		package_check_installed $packages_common
		package_check_files $packages_owning_files
	fi
}

check_local_logrotate() {
	# check if log rotation available
	if [ ! -x /usr/sbin/logrotate ]; then
		log info "log rotation support not installed"
		return
	fi

	# do a dry-run of logrotate
	/usr/sbin/logrotate -df /etc/logrotate.conf >/dev/null 2>&1
	rc=$?

	if [ $rc -eq 0 ]; then
		log pass "log rotation works correctly"
	else
		log fail "log rotation fails - try '/usr/sbin/logrotate -df /etc/logrotate.conf'"
	fi
}

check_local() {
	check_local_platform
	[ -n "$strict" ] && check_local_libraries
	check_local_hosts
	
	check_local_group
	rc_grp=$?
	
	check_local_user
	rc_usr=$?

	# check membership if both functions returned success
	if [[ ("$rc_grp" -eq 0) && ("$rc_usr" -eq 0) ]]; then
		check_local_membership
		rc_member=$?
	fi

	if [ -n "$administration" ]; then
		if [[ ("$rc_grp" -eq 1) || ("$rc_usr" -eq 1) || ("$rc_member" -eq 1) || (-n "$force") ]]; then
			# if adding non-rms user, only admin the user
			if [ -n "$user_name" ]; then
				admin_remove
				admin_add_user
			else
				admin_remove
				admin_add_group
				admin_add_user
				admin_add_membership
			fi
		else
			log info "not performing user/group administration (use -f to force)"
		fi
	fi
	
	# verify packages
	package_check_deprecated
	check_local_packages

	# check log rotation
	check_local_logrotate
}

###

check_rmshost_database() {
	# check for existence of 'rmstbladm'
	which rmstbladm >/dev/null 2>&1
	rc=$?

	if [ $rc -ne 0 ]; then
		log fail "unable to check database integrity ('rmstbladm' not found)"
		return
	fi

	# tests database integrity - warnings are OK
	result=`rmstbladm 2>&1`
	rc=$?
	
	if [ $rc -eq 0 ]; then
		log pass "database integrity good"
	else
		log fail "database integrity failure ($result)"
	fi
}

check_rmshost_packages() {
	package_check_installed $packages_rmshost
}

check_rmshost_nodes() {
	build_node_list
	rc=$?

	# check if unable to find nodes
	if [ $rc -ne 0 ]; then
		exit 1
	fi
	
	base_options="-x -r $rmshost_addr -k '$local_kernel_sum'"

	# if valid OS string found
	[ -n "$local_os_sum" ] && base_options="$base_options -o '$local_os_sum'"

	# if rms group member list exists
	[ -n "$local_group_members" ] && base_options="$base_options -b '$local_group_members'"

	# if package list available
	[ -n "$local_package_versions" ] && base_options="$base_options -d $local_package_versions"

	# if rms group exists
	[ -n "$group_gid" ] && base_options="$base_options -g $group_gid"

	# if rms user exists
	[ -n "$user_gid" ] && base_options="$base_options -u $user_gid"

	# if verbose is enabled, pass on the flag
	[ -n "$verbose" ] && base_options="$base_options -v"
	
	# if package checking is enabled, pass on the flag
	[ -n "$no_check_packages" ] && base_options="$base_options -c"
	
	# if administration is enabled, pass on the flag
	[ -n "$administration" ] && base_options="$base_options -a"
	
	# if force administration is enabled, pass on the flag
	[ -n "$force" ] && base_options="$base_options -f"
	
	# if username is specified, add it
	[ -n "$user_name" ] && base_options="$base_options -n$user_name"
	
	# initialise 'netid'
	netid_current=`rmsquery "select netid from nodes where name='$rmshost'" 2>&1`
	if [[ ( $? -ne 0 ) || ( "$netid_current" = "Null" ) ]]; then
		log info "skipping network position checking (netid unavailable from database)"
		netid_current="(unknown)"
	fi

	# run script on all nodes
	for node in $node_list; do
		# skip and nodes that are ourselves
		if [ "$machine_name$node" == "$hostname" ]; then
			continue
		fi
		
		log "[$machine_name$node]"
		
		# check 'netid' is positive monotonic
		check_rmshost_nodes_netid $machine_name$node

		# get per-host information
		host_addr=`getent hosts $machine_name$node | $AWK '{print $1}'`
		
		# calculate time every iterations, to avoid checking against stale time
		rmshost_time=`date +%Y/%m/%d.%H:%M`
		
		# add options
		options="$base_options -t $rmshost_time -e $host_addr -y $machine_name$node"
		
		rsh $node_prefix$machine_name$node$node_suffix $prog_path $options
	done

	# success
	return 0
}

check_rmshost_nodes_netid() {
	local node=$1
	# var 'netid_current' holds last value

	# skip check if database previously unavailable
	if [ "$netid_current" = "(unknown)" ]; then
		return
	fi

	local netid_node=`rmsquery "select netid from nodes where name='$node'" 2>&1`
	if [ $? -ne 0 ]; then
		log info "skipping local network position check (netid unavailable from database)"
	fi

	# a 'Null' netid is fine - skip check
	if [ "$netid_node" = "Null" ]; then
		log pass "network position not found - skipping"
		return
	fi

	if [ $netid_node -gt $netid_current ]; then
		log pass "network position in sequence in database (local $netid_node, last $netid_current)"
		netid_current=$netid_node
	else
		log fail "network position out of sequence in database (local $netid_node, last $netid_current)"
	fi
}

check_rmshost() {
	# rmshost specific tests
	check_rmshost_database

	# verify packages
	[ -z "$no_check_packages" ] && check_rmshost_packages

	# remote tests for all nodes
	check_rmshost_nodes
}

###

check_remote_time() {
	rmshost_time=$1	
	local_time=`date +%Y/%m/%d.%H:%M`
	
	if [ "$local_time" != "$rmshost_time" ]; then
		log fail "local time different than rmshost time"
	else
		log pass "local time synchronous to rmshost time"
	fi
}

check_remote_rmshost() {
	hosts_rmshost_addr=$1
	
	if [ "$hosts_rmshost_addr" != "$rmshost_addr" ]; then
		log fail "local 'rmshost' IP address different that on 'rmshost' (local '$rmshost_addr', rmshost '$hosts_rmshost_addr')"
	else
		log pass "local 'rmshost' definition same as on 'rmshost'"
	fi
}

check_remote_host() {
	hosts_host_line=`getent hosts $hostname`
	hosts_host_addr=`echo $hosts_host_line | $AWK '{print $1}'`
	
	host_addr=$1
	
	if [ "$hosts_host_addr" != "$host_addr" ]; then
		log fail "hostname IP address different than on 'rmshost' (local '$hosts_host_addr', rmshost '$host_addr')"
	else
		log pass "hostname IP address same as on 'rmshost'"
	fi

	# check rmshost view of node's hostname w.r.t. local hostname
	if [ "$node_hostname" != "$hostname" ]; then
		log fail "local hostname different than rmshost's hosts file (local '$hostname', rmshost '$node_hostname')"
	else
		log pass "local hostname consistent with rmshost's hosts file ('$hostname')"
	fi
}

check_remote_kernel() {
	local rmshost_kernel_sum=$1
		
	if [ "$local_kernel_sum" != "$rmshost_kernel_sum" ]; then
		log fail "local kernel version different than on rmshost '$local_kernel_string'"
	else
		log pass "local and rmshost kernel version identical"
	fi
}

check_remote_os() {
	local rmshost_os_sum=$1
		
	# skip checks where remote release unknown
	[ -z "$local_os_sum" ] && return

	if [ "$local_os_sum" != "$rmshost_os_sum" ]; then
		log fail "local OS version different than on rmshost '$local_os_string'"
	else
		log pass "local and rmshost OS version identical"
	fi
}

check_remote_grpmembers() {
	rmshost_group_members=$1
	
	if [ "$local_group_members" != "$rmshost_group_members" ]; then
		log fail "local group 'rms' members are different than on rmshost (local '$local_group_members', rmshost '$rmshost_group_members')"
	else
		log pass "local and rmshost group 'rms' members identical"
	fi
}

check_remote_package_versions() {
	# can't check if there was a problem getting package versions
	[ -z "$local_package_versions" ] && return

	local local_vers=( )
	local index=0
	
	for elem in `echo $local_package_versions | tr '+' ' '`; do
		local_vers[$index]=$elem
	
		index=`expr $index + 1`
	done

	index=0

	for elem in `echo $rmshost_package_versions | tr '+' ' '`; do
		local_version=${local_vers[$index]}

		if [ "$elem" != "$local_version" ]; then
			local localpkg_name=`echo "$local_version" | cut -d'@' -f1`
			local localpkg_date=`echo "$local_version" | cut -d'@' -f2`

			# check for a single copy of package installed
			echo "$localpkg_date" | grep '[^0-9]' >/dev/null
			if [ $? -eq 0 ]; then
				log fail "multiple $localpkg_name packages installed"

				# must increment before continuing
				index=`expr $index + 1`

				continue
			fi

			local localpkg_datestr=`date -d "1970-01-01 UTC $localpkg_date seconds" +"%Y-%m-%d %T"`
			
			local pkg_name=`echo "$elem" | cut -d'@' -f1`
			local pkg_date=`echo "$elem" | cut -d'@' -f2`
			local pkg_datestr=`date -d "1970-01-01 UTC $pkg_date seconds" +"%Y-%m-%d %T"`
			
			log fail "'$localpkg_name' ($localpkg_datestr) differs from rmshost:'$pkg_name' ($pkg_datestr)"
		fi

		index=`expr $index + 1`
	done
}
		
check_remote() {
	# time check
	if [ -n "$remote_time" ]; then
		check_remote_time $remote_time
	fi
	
	# rmshost check
	if [ -n "$remote_rmshost_addr" ]; then
		check_remote_rmshost $remote_rmshost_addr
	fi
	
	# host check
	if [ -n "$remote_host_addr" ]; then
		check_remote_host $remote_host_addr
	fi
			
	# kernel version check
	if [ -n "$remote_kernel_sum" ]; then
		check_remote_kernel $remote_kernel_sum
	fi

	# os version check
	if [ -n "$remote_os_sum" ]; then
		check_remote_os $remote_os_sum
	fi

	# rms group members
	if [ -n "$remote_group_members" ]; then
		check_remote_grpmembers $remote_group_members
	fi

	# package version check
	if [ -n "$rmshost_package_versions" ]; then
		check_remote_package_versions $rmshost_package_versions
	fi
}

###

check() {
	if [ -z "$remote_tests" ]; then
		log "[$hostname]"
	fi
	
	# run local tests
	check_local
	
	# run rmshost tests, if appropriate
	if [ -n "$rmshost_local" ]; then
		check_rmshost
	fi

	# run remote tests, if appropriate
	if [ -n "$remote_tests" ]; then
		check_remote
	fi
}

###

log() {
	case "$1" in
	fail)
		printf -- " ! $2\n" 1>&2
		;;
	pass)
		[ -n "$verbose" ] && printf -- " - $2\n" 1>&2
		;;
	info)
		printf -- " * $2\n" 1>&2
		;;
	*)	
		# log normal messages
		printf -- "$1\n" 1>&2
	esac
}

help() {
	if [ "$prog_name" = "rmssetup" ]; then
		log "Usage: $prog_name [-fhv] [-N <nodelist>] [-n <username>] [-p <node prefix>] [-s <node suffix>] [-u <user id>]"
	else
		log "Usage: $prog_name [-chv] [-N <nodelist>] [-p <node prefix>] [-s <node suffix>]"
	fi

	if [ "$prog_name" = "rmscheckenv" ]; then
		log "\t-c                   skip package verification"
	fi
	
	if [ "$prog_name" = "rmssetup" ]; then
		log "\t-f                   force removal and creation of RMS admin user 'rms' and group 'rms'"
	fi
	
	log "\t-h                   help"
	log "\t-N <nodelist>        nodes to check"
	
	if [ "$prog_name" = "rmssetup" ]; then
		log "\t-n <username>        create user <username> with RMS admin prividges"
	fi
	
	log "\t-p <node prefix>     string to prefix nodename"
	log "\t-s <node suffix>     string to suffix nodename"
	
	if [ "$prog_name" = "rmssetup" ]; then
		log "\t-u <uid>             create user with user id <uid> and RMS admin prividges"
	fi
	
	log "\t-v                   verbose operation"
	log "For internal use only:"
	
	if [ "$prog_name" = "rmssetup" ]; then
		log "\t-a -b -c -d -e -g -k -o -r -t -x -y"
	else
		log "\t-a -b -d -e -f -g -k -n -o -r -t -u -x -y"
	fi	
	
	exit 1
}

package_check_deprecated() {
	# check for legacy 'QSW' packages
	local packages_1=`rpm -qa 2>&1 | grep "^qsw" | tr '\r\n' ','`
	if [ "$packages_1" != "" ]; then
		log fail "deprecated packages found ($packages_1)"
	fi

	local packages_2=`rpm -q $packages_deprecated 2>&1 | grep -v 'not installed' | tr '\r\n' ','`
	if [ "$packages_2" != "" ]; then
		log fail "deprecated packages found ($packages_2)"
	fi
}

package_check_installed() {
	local packages=$*

	for package in $packages; do
		# test if package is installed
		local result=`rpm -q $package 2>&1`

		if [ $? -eq 0 ]; then
			if [ "$result" != "package $package is not installed" ]; then
				# verify package, returning failed status string
				local pkg_stat=`rpm -V $package 2>&1`

				if [ $? -eq 0 ]; then
					if [ "$pkg_stat" = "" ]; then
						log pass "'$package' verifies correctly"
					else
						log fail "'$package' fails verification"
						log "     (`echo $pkg_stat`)"
					fi
				else
					# if we are local, ie rsh was not used, then rpm returns 1 for a package mis-installed
					log fail "'$package' fails verification"
					log "     (`echo $pkg_stat`)"
				fi
			else
				log fail "'$package' not installed"
			fi
		else
			log fail "'$package' not installed"
		fi
	done
}

package_check_files() {
	local files=$*

	for file in $files; do
		# test if package is installed
		local pkg_name=`rpm -qf $file 2>&1`

		if [ $? -eq 0 ]; then
			if [ "$pkg_name" != "error: file $file: No such file or directory" ]; then
				# verify package, returning failed status string
				local pkg_stat=`rpm -Vf $file 2>&1`

				if [ $? -eq 0 ]; then
					if [ "$pkg_stat" = "" ]; then
						log pass "'$pkg_name' (owning $file) failed verification"
					else
						log fail "'$pkg_name' (owning $file) failed verification"
						log "     (`echo $pkg_stat`)"
					fi
				else
					# if we are local, ie rsh was not used, then rpm returns 1 for a package mis-installed
					log fail "'$pkg_name' (owning $file) failed verification"
					log "     (`echo $pkg_stat`)"
				fi
			else
				log fail "package owning $file not installed"
			fi
		else
			log fail "package owning $file not installed"
		fi
	done
}

package_get_versions() {
	local packages=$*
	local ver_list
	local not_installed
		
	for package in $packages; do
		# get package version string
		local ver=`rpm -q --qf '%{NAME}-%{VERSION}-%{RELEASE}@%{BUILDTIME}' $package 2>&1`
		if [ $? -ne 0 ]; then
			log fail "failed to get common package versions ($ver)"
			return
		fi

		# check if package is not installed
		echo $ver | grep "not installed" >/dev/null 2>&1
		if [ $? -ne 1 ]; then
			if [ -z "$not_installed" ]; then
				not_installed="$package"
			else
				not_installed="$not_installed $package"
			fi
		fi

		# build up version list string
		if [ -z "$ver_list" ]; then
			ver_list="$ver"
		else
			ver_list="$ver_list+`echo "$ver"`"
		fi
	done

	# print and return if packages are not all installed
	if [ -n "$not_installed" ]; then
		log fail "packages '$not_installed' not installed"
		return
	fi
	
	local_package_versions=$ver_list
}

collapse_hostnames() {
	local msnodes=""

	for host in $1; do
		# strip the digits
		local hname=`echo $host | sed "s/[0-9]*\$//"`
		local hid=`echo $host | sed "s/\$hname//"`

		if [ "$hid" = "" ]; then
			if [ "$msnodes" = "" ]; then
				msnodes="$host"
			else
				msnodes=" ${msnodes}$host"
			fi
		else
			hostnames[$hid]=$host
		fi
	done

	# now create the hostnamelist
	basename=""
	hlist=""
	firstid=""
	lastid=""
	range=0

	if [ "${hostnames[*]}" != "" ]; then
		for host in ${hostnames[*]}; do
			hname=`echo $host | sed "s/[0-9]*\$//"`
			hid=`echo $host | sed "s/\$hname//"`

			if [ "$basename" = "" ]; then
				basename=$hname
				firstid=$hid
				lastid=$hid
				range=0
				
				if [ "$hlist" = "" ]; then
					hlist="$basename"
				else
					hlist="$hlist $basename"
				fi
			else
				if [ "$basename" != "$hname" ]; then
					return ""  # this is an ERROR RMCDEBUG
				else
					if [ $hid -eq `expr $lastid + 1` ]; then
						lastid=$hid
					else
						# next hostname is not in current range
						if [ $range -eq 0 ]; then
							hlist="${hlist}["
							range=1
						fi

						if [ $firstid -eq $lastid ]; then
							hlist="${hlist}${firstid},"
						else
							hlist="${hlist}${firstid}-${lastid},"
						fi

						firstid=$hid
						lastid=$hid
					fi
				fi
			fi
		done

		if [ $firstid -eq $lastid ]; then
			if [ $range -eq 0 ]; then
				hlist="$hlist${firstid}"
			else
				hlist="$hlist${firstid}]"
			fi
		else
			if [ $range -eq 0 ]; then
				hlist="$hlist[${firstid}-${lastid}]"
			else
				hlist="$hlist${firstid}-${lastid}]"
			fi
		fi
	fi

	if [ "$msnodes" = "" ]; then
		echo "$hlist"
	else
		echo "$hlist $msnodes"
	fi
}

expand_hostnames() {
	echo "`echo "$1" | $AWK -f $parser`"
}

build_node_list() {
	# check for existence of 'rmsquery'
	which rmsquery >/dev/null 2>&1
	rc=$?

	if [ $rc -ne 0 ]; then
		log fail "unable to get node list ('rmsquery' not found)"
		exit 1
	fi

	# use optional node list
	if [ -n "$node_list_opt" ]; then
		node_list=`expand_hostnames "$node_list_opt"`
		return 0
	fi
	
	# get machine name
	machine_name=`rmsquery "select val from attributes where name='name'" 2>&1`
	[ $? -ne 0 ] && log fail "unable to get machine name ($machine_name)" && return 1

	# get node list from database
	node_list=`rmsquery "select name from nodes where name<>'$rmshost'" 2>&1 | sed s/$machine_name// | sort -n`
	rc=$?
		
	# check for rmsquery failure
	if [ $rc -ne 0 ]; then
		log fail "unable to get node list from database ($node_list)"
		return 1
	fi

	# check for nodes
	if [ "$node_list" = "" ]; then
		log info "no compute nodes to work on"
	fi	
	
	# get node suffix and prefix from database
	if [ -z "$node_prefix" ]; then
		node_prefix=`rmsquery "select val from attributes where name='rms-hostname-prefix'"`
	fi
	
	if [ -z "$node_suffix" ]; then
		node_suffix=`rmsquery "select val from attributes where name='rms-hostname-suffix'"`
	fi
	
	return 0
}

initialise() {
	prog=$0
	prog_dir=`dirname $prog`
	prog_name=`basename $prog`
	
	# sanity checks
	if [[ "$prog_name" != "rmssetup" && "$prog_name" != "rmscheckenv" ]]; then
		log "program name should be 'rmssetup' or 'rmscheckenv' (not $prog_name)"
		exit 1
	fi
	
	here=`pwd`

	if [ `printf "$prog\n" | grep -v "^/"` ]; then
		if [ "$prog_dir" = "" -o "$prog_dir" = "." ]; then
			productbase=$here
		else
			productbase=$here/$prog_dir
		fi
	else
		productbase=$prog_dir
	fi

	prog_path=$productbase/$prog_name
	
	# if running as 'rmssetup', administer user/group
	if [ "$prog_name" == "rmssetup" ]; then
		administration="y"
	fi

	hostname=`hostname`

	# parse options
	while getopts "ab:cd:e:fg:hk:n:N:o:p:r:s:t:u:vxy:" option; do
		case $option in
			a )
			administration="y"
			;;
			b )
			remote_group_members=$OPTARG
			;;
			c )
			no_check_packages="y"
			;;
			d )
			rmshost_package_versions=$OPTARG
			;;
			e )
			remote_host_addr=$OPTARG
			;;
			f )
			force="y"
			;;
			g )
			remote_gid=$OPTARG
			;;
			h )
			help
			;;
			k )
			remote_kernel_sum=$OPTARG
			;;
			n )
			user_name=$OPTARG
			;;
			N )
			node_list_opt=$OPTARG
			;;
			o )
			remote_os_sum=$OPTARG
			;;
			p )
			node_prefix=$OPTARG
			;;
			r )
			remote_rmshost_addr=$OPTARG
			;;
			s )
			node_suffix=$OPTARG
			;;
			t )
			remote_time=$OPTARG
			;;
			u )
			remote_uid=$OPTARG
			;;
			v )
			verbose="y"
			;;
			x )
			remote_tests="y"
			;;
			y )
			node_hostname=$OPTARG
			;;
			* )
			help
			;;
		esac
	done

	# check if used has invoked 'for internal use only' options
	if [[ -z "$remote_tests" && ( -n "$remote_host_addr" || -n "$remote_gid" || -n "$remote_kernel_sum" || -n "$remote_os_sum" || -n "$remote_rmshost_addr" || -n "$remote_time" || -n "$remote_uid" ) ]]; then
		help
	fi
	
	# move argument pointer to point to next non-option argument
	shift $(($OPTIND - 1))
	
	# test for further arguments
	if [ "$1" != "" ]; then
		help
	fi
	
	# set awk nodelist parser path
	parser="./parsenodelist.awk"
	if [ ! -f $parser ]; then
		parser="/usr/lib/rms/bin/parsenodelist.awk"
	fi

	# print banner
	if [ -z "$remote_tests" ]; then
		log "Checking RMS environment on `date +'%d/%m/%Y %H:%M'`"
		log "--------------------------------------------"
	fi

	# default package lists
	packages_rmshost="qsflexlm qsjre qsmsql qsrms qsui"
	packages_common="qsmsqllib qsnetdiags qsnet-headers qsnetlibs qsnetmpi qsnetutils qsquery qsrmsauth qsrmslibs qsrmsman qsswm"
	packages_common_optional="qsnetdevkit qsnet2diagscommon qsnet2libs"
	packages_deprecated="qsswmex qsnet-RedHat-kernel-headers qsnet-RedHat-kernel-doc"
	packages_owning_files="/lib/modules/`</proc/sys/kernel/osrelease`"

	# exceptions
	[ `uname -m` = "x86_64" ] && packages_deprecated="$packages_deprecated qsui"

	# default user/group settings
	default_gid=170
	default_uid=170

	# if user_name is undefined, default to user 'rms'
	if [ -n "$user_name" ]; then
		user=$user_name
	else
		user="rms"
	fi
}

admin_remove() {
	# only remove everything if user is 'rms'
	if [ "$user" == "rms" ]; then
		# remove group 'rms' and user 'rms'
		userdel $user 2>/dev/null 1>&2
	
		if [ "$user_exists" != "no" ]; then
			log info "removed user '$user'"
		fi
		
		groupdel $user 2>/dev/null 1>&2
		
		if [ "$group_exists" != "no" ]; then
			log info "removed group '$user'"
		fi
		
	else
		userdel -r $user 2>/dev/null 1>&2
		
		if [ "$user_exists" != "no" ]; then
			log info "removed user '$user' entries"
		fi
	fi	
}

admin_add_group() {
	if [ -n "$remote_gid" ]; then
		group_gid=$remote_gid
	else
		group_gid=$default_gid
	fi
	
	# '-o' required, since gid 170 may exist in NIS
	result=`groupadd -g $group_gid -o rms 2>&1`
	rc=$?	
	
	if [ $rc -eq 0 ]; then
		log info "added group 'rms' (gid $group_gid)"
	else
		log fail "failed to add group 'rms' with gid $group_gid ($result)"
	fi
}

admin_add_user() {
	if [ -n "$remote_uid" ]; then
		user_uid=$remote_uid
	else
		user_uid=$default_uid
	fi

	# if user is 'rms', group 'rms' is its primary group	
	if [ "$user" == "rms" ]; then
		# -r means create system account and deprecates -M here
		result=`useradd -c "RMS System Account" -g rms -u $user_uid -d / -s /bin/false $user 2>&1`
		rc=$?
	else
		result=`useradd -g users -G rms -m -d /tmp/$user -u $user_uid $user 2>&1`
		rc=$?
	fi		
	
	if [ $rc -eq 0 ]; then
		log info "added user '$user' with pri group 'rms' (uid $user_uid)"
	else
		log fail "failed to add user '$user' with pri group 'rms' and uid $user_uid ($result)"
	fi
}

admin_add_membership() {
	local groups=`id -Gn root | tr ' ' ','`
	result=`usermod -G $groups,rms root 2>&1`
	rc=$?	
	
	if [ $rc -eq 0 ]; then
		log info "added user 'root' to group 'rms'"
	else
		log fail "failed to add user 'root' to group 'rms' ($result)"
	fi
}

###

# ensure binaries are found in expected places
PATH=/bin:/usr/bin:/sbin:/usr/sbin

initialise $*
check
