:
#  ident "@(#)naddgroup.sh	1.1 91/02/21 "
#  (C) Copyright Altos Computer Systems, 1990.
#	All rights reserved.

#
# Add a UNIX group.
# usage: naddgroup [ -d | -g gid | -m members ] groupname
#
#	-d 	Delete the group.
#		This option cannot be used with -g or -m.
#
#	-g	Create the group with the given gid.
#		If -g is not specified, the group's id is 
#		determined automatically.
#
#	-m	Create the group with the given member list.
#		The member list is a set of comma-separated users.
#		If -m is not specified, the member list is null.
#	



PATH=/bin:/usr/bin:/etc:$PATH:
COMMAND=`basename $0`
OPTIONS="dg:m:"
USAGE="usage:  $COMMAND [ -d | -g gid | -m members ] groupname"
GROUP_FILE="/etc/group"
MIN_GID=100
MAX_GID=60000



#
# Parse the command line options
#

DFLAG=false
GFLAG=false
MFLAG=false
MEMBERS=""

while getopts $OPTIONS opt
do
	case $opt in
		 d)	DFLAG=true
			;;

		 g)	GFLAG=true
			GID=$OPTARG
			expr $GID + 0 >/dev/null 2>&1 
			if [ $? -ne 0 -o "$GID" -lt 0 -o $GID -ge $MAX_GID ]
			then
				echo "$COMMAND: bad gid ($GID)" 
				echo $USAGE
				exit 1
			fi
			;;

		m)	MFLAG=true
			MEMBERS=$OPTARG
			;;

		\?)	echo $USAGE
			exit 1
			;;
	esac
done
shift `expr $OPTIND - 1`
GROUP=$1


if [ -z "$GROUP" ]
then
	echo $USAGE
	exit 1
elif echo $GROUP | fgrep : >/dev/null 2>&1
then
	echo "$COMMAND: colons(:) cannot be embedded in the group name."
	exit 1
elif $DFLAG && ( $GFLAG || $MFLAG )
then
	echo "$COMMAND: -d cannot be used with -g or -m."
	echo "$USAGE"
	exit 1
fi




#
# if DFLAG is set, delete GROUP from GROUP_FILE
#

if $DFLAG
then
	if grep "^$GROUP:" $GROUP_FILE >/dev/null 2>&1
	then
		ed $GROUP_FILE >/dev/null 2>&1 <<-EOF
			/^$GROUP:
			d
			w
			q
			EOF

		if [ $? -ne 0 ]
		then
			echo "$COMMAND: \c"
			echo "could not delete group $GROUP."
			exit 1
		fi
	fi
else


	#
	# We're adding GROUP;
	# Check if it already exists in GROUP_FILE
	#

	if grep "^$GROUP:" $GROUP_FILE >/dev/null 2>&1
	then
		echo "$COMMAND: \c"
		echo "group $GROUP already exists."
		exit 1
	fi


	#
	# The group does not exist.
	# Create the gid and add the group
	#

	if $GFLAG
	then
		#
		# The user specified a gid;
		# Check if it's already being used
		#

		if grep ":$GID:" $GROUP_FILE >/dev/null
		then
			echo "$COMMAND: \c"
			echo "gid $GID already in use;  \c"
			echo "group $GROUP not added."
			exit 1
		fi
	else
				
		#
		# Choose the next available gid
		#

		GID=`awk -F":" '{ print $3 }' $GROUP_FILE | sort -n | tail -1`
		GID=`expr $GID + 1`
		if [ $GID -lt $MIN_GID ]
		then
			GID=$MIN_GID
		fi
	fi


	#
	# Add the group
	#

	echo "$GROUP::$GID:$MEMBERS" >> $GROUP_FILE
fi
exit 0

