#!/bin/ksh -p
#
# ident "@(#)utadminuser.ksh	1.3	05/04/01 SMI"
#
# Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#


PATH=/bin:/usr/bin:/sbin:/usr/sbin
PROG=${0##*/}
ERROR_PREF="${PROG}:"
BASEDIR=/etc/opt/SUNWut/basedir
UTPROP=${BASEDIR}/lib/utprop

#DEBUG="set -x"	# uncomment this line to turn on debugging

OS=`uname`
if [ $OS = "Linux" ]
then
	NAWK=/usr/bin/gawk
else
	NAWK=/usr/bin/nawk
fi

#
# Usage - prints the usage message
# $1 - the exit code
Usage() {
	typeset OUT=""

	if [[ $1 -ne 0 ]]; then
		OUT="-u2"
	fi
	print ${OUT} "
	${PROG}
	${PROG} -h
	${PROG} -a <username> [ <username> ... ]
	${PROG} -d <username> [ <username> ... ]
	${PROG} -r

	Options:
		# with no options, ${PROG} prints the list of all users
		# authorized to administer the Sunray through the Admin GUI.
	-a	# adds specified users to the list
	-d	# deletes specified users from the list
	-r	# removes all authorized users
	-h	# prints this usage
	"

	exit $1
}


#
# setOP - makes sure that only one option is specified.
#
setOP() {
	if [[ -z "$OPMODE" ]]; then
		OPMODE=$1
	elif [[ "$OPMODE" = "$1" ]]; then
		print -u2 "only one instance of -${1} is allowed"
		Usage 1
	else
		print -u2 "conflicting options -${OPMODE} and -${1}"
		Usage 1
	fi
}


#
# list_user - lists all the authorized users
#
list_user() {
	$UTPROP -k AdminUsers 2> /dev/null | tr " " "\n"
	return 0
}

#
# is_valid_user - check for valid username
# We enforce the similar rule defined in useradd(1M).  The username must
# be string consting of characters from the set of alphabetic characters,
# numeric characters, period (.), underscore (_), and hyphen (-). The
# first character should be alphabetic.
#
# Parameter:
#	$1: the username to be verified
#
is_valid_user() {
	if [ $# -eq 0 ]; then
		return 1
	fi
	expr $1 : '\([a-zA-Z][0-9a-zA-Z\._-]*\)$' > /dev/null 2>&1
	return $?
}

#
# add_user - add users to the authorized list
#
add_user() {
	typeset LIST=`$UTPROP -k AdminUsers 2> /dev/null`
	typeset ADDING="false"

	for u in $*
	do
		if ! is_valid_user $u; then
			print -u2 "Skipping invalid username $u."
			continue
		fi
		NEWLIST=`print $LIST | \
		${NAWK} -F' ' '
		BEGIN	{found = 0; sep = ""}
			{
			    for (i = 1; i <= NF; i++) {
				if ($i == user) {
				    found = 1
				}
				printf ("%s%s", sep, $i)
				if (i == 1) {
				    sep = " "
				}
			    }
			}
		END	{
			    if (found == 0) {
				printf("%s%s", sep, user)
			    	exit(0)
			    }
			    exit(1)
			}' user=$u`

		if [ $? -eq 0 ]; then
			print "Adding user $u ..."
			ADDING="true"
		else
			print "User $u already in the list"
		fi
		LIST=${NEWLIST}
	done
	if ${ADDING}; then
		$UTPROP -a -f AdminUsers "$LIST" 2> /dev/null
		ret=$?
		if [ $ret -ne 0 ]; then
			print -u2 "Failed to add user(s) to the list"
		else
			print "User(s) added successfully!"
		fi
		return $ret
	fi
	return 0
}

#
# delete_user - deletes users from the authorized list
#
delete_user() {
	typeset LIST=`$UTPROP -k AdminUsers 2> /dev/null`
	typeset DELETING="false"

	if [ $# -eq 0 ]; then
		if [ -n "$LIST" ]; then
			# removing all users
			$UTPROP -d AdminUsers 2> /dev/null
			ret=$?
		else
			# just to print the successful message even if
			# no users are currently defined
			ret=0
		fi
		if [ $ret -ne 0 ]; then
			print -u2 "Failed to delete the Admin user list"
		else
			print "Admin user list deleted successfully!"
		fi
		return $ret
	fi
	
	for u in $*
	do
		if ! is_valid_user $u; then
			print -u2 "Skipping invalid username $u."
			continue
		fi
		NEWLIST=`print $LIST | \
		${NAWK} -F' ' '
		BEGIN	{found = 0; sep = ""}
			{
			    for (i = 1; i <= NF; i++) {
				if ($i == user) {
				    found = 1
				} else {
				    printf ("%s%s", sep, $i)
				    sep = " "
				}
			    }
			}
		END	{
			    if (found == 0) {
			    	exit(1)
			    }
			    exit(0)
			}' user=$u`

		if [ $? -eq 0 ]; then
			print "Deleting user $u ..."
			DELETING="true"
		else
			print "User $u is not in the list"
		fi
		LIST=${NEWLIST}
	done
	if ${DELETING}; then
		if [ -n "${LIST}" ]; then
			$UTPROP -a -f AdminUsers "$LIST" 2> /dev/null
		else
			$UTPROP -d AdminUsers 2> /dev/null
		fi
		ret=$?
		if [ $ret -ne 0 ]; then
			print -u2 "Failed to delete user(s) from the list"
		else
			print "User(s) deleted successfully!"
		fi
		return $ret
	fi
	return 0
}



#
# mustBeRoot - make sure the user has root priledge
function mustBeRoot {
        case "$(id)" in
        'uid=0('*)
                ;;
        *)
                print -u2 "${ERROR_PREF} Must be root to update the Admin user list"
                exit 1
                ;;
        esac
}


#
# mustBeConfigured - make sure the server is configured
function mustBeConfigured {
	if [ ! -f /etc/opt/SUNWut/utadmin.conf ]; then
                print -u2 "${ERROR_PREF} Please run Sun Ray server configuration utility utconfig\n"\
		"before using $PROG."
                exit 1
	fi
}


OPMODE=""

while getopts "adrh" c
do
	case $c in
	a)	setOP "a";;
	d)	setOP "d";;
	r)	setOP "r";;
	h)	setOP "h";;
	*)	print -u2 "${ERROR_PREF} Invalid option."
		Usage 1;;
	esac
done

shift `expr $OPTIND - 1`

case "${OPMODE}" in
"" | h | r)	# operations that do no require any extra argument
	if [[ $# -gt 0 ]]; then
		print -u2 "${ERROR_PREF} extra arguments found"
		print -u2 "\tArguments: $*"
		Usage 1
	fi
	case "${OPMODE}" in
	"")	# display list of authorized users
		mustBeConfigured
		list_user;;
	h)	# print usage
		Usage 0;;
	r)	# remove all users
		mustBeRoot
		mustBeConfigured
		delete_user;;
	esac;;
a | d)	mustBeRoot
	mustBeConfigured
	# add/delete operation requires at least one extra argument
	if [[ $# -lt 1 ]]; then
		print -u2 "${ERROR_PREF} missing username(s)."
		Usage 1
	fi
	USERS="$*"
	case "${OPMODE}" in
	a)	# add users
		add_user $USERS;;
	d)	# delete users
		delete_user $USERS;;
	esac;;
esac

exit $?
