# Add a User
# Copyright 1986 L/F Technologies, Carson City, Nevada
#
# Created:	 10-Dec-86
# Modified Date: 09-Nov-87
#
# Created By:	 Rodger Lakey
# Modified By:	 Sandy Marshall
#

while :
do
	echo "Enter login name: \c"
	read LOGNAME
	if [ -n "$LOGNAME" ]
	then 
   		EXISTS=`grep -c "^$LOGNAME:" /etc/passwd`
   		if [ "$EXISTS" = "0" ]
		then
			break
		else
			echo "\nThat name is already in use\n"
		fi
	else	exit 1
	fi
done

read NEXTID < /etc/.nextid
while :
do
	echo "\nEnter the userid number (default $NEXTID): \c"
	read UID
	if [ -n "$UID" ]
	then
		EXISTS=`awk -F: '{ if ( $3 == x ) printf("%s ",$1) }' x=$UID /etc/passwd`
		if [ "$EXISTS" != "" ]
		then
			echo "\nThat userid is already in use"
			echo "Type \"yes\" if this is the correct id: \c"
			read ANS
			if [ "$ANS" = "yes" ]
			then
				break
			fi
		else
			break
		fi
	else
		UID=$NEXTID
		NEXTID=`awk '{ printf("%d",$1+1) }' /etc/.nextid`
		echo $NEXTID > /etc/.nextid
		break
	fi
done

while :
do
	echo "\nEnter the groupid number (default 100): \c"
	read GID
	if [ -n "$GID" ]
	then	EXISTS=`awk -F: '{ if ( $3 == x ) printf("%s ",$1)}' x=$GID /etc/group`
		if [ "$EXISTS" = "" ]
		then
			echo "\nThat group does not exist"
		else
			break
		fi
	else	GID=100
		break
	fi
done

echo "\nEnter user profile (full name, phone ext.): \c"
read FULLNAME

while :
do
	echo "\nEnter home directory (default /usr/$LOGNAME): \c"
	read HOMEDIR
	if [ -n "$HOMEDIR" ]
	then
		if [ -x $HOMEDIR ]
		then
			echo "\nThat directory already exists"
			echo "It's ownership and permissions will not be changed."
			echo "Type \"yes\" if this is correct: \c"
			read ANS
			if [ "$ANS" = "yes" ]
			then
				break
			fi
		else
			break
		fi
	else	HOMEDIR=/usr/$LOGNAME
		break
	fi
done

while :
do
	echo "\nEnter the shell program you wish to assign to"
	echo "this user (default /usr/bin/cube.sh): \c"
	read LSHELL
	if [ -z "$LSHELL" ]
	then
		LSHELL=/usr/bin/cube.sh
	fi
	if [ -x $LSHELL ]
	then
		break
	else
		echo "\nThat program does not exist"
	fi
done

while :
do
	if mkdir /etc/ptmp		# fails if passwd file is in use
	then
		cp /etc/passwd /etc/opasswd
		chmod 444 /etc/opasswd
		chmod 600 /etc/passwd
		echo $LOGNAME::$UID:$GID:$FULLNAME:$HOMEDIR:$LSHELL |
			sort -t: +2n /etc/opasswd - > /etc/passwd
		chmod 444 /etc/passwd
		rmdir /etc/ptmp
		break
	else
		echo "/etc/passwd is currently in use"
		echo "If you wish to try adding the new user's account again,"
		echo "please type \"yes\""
		read ANS
		if [ "$ANS" = "yes" ]
		then	continue
		else	echo "\nThe new account has not been added"
			exit 1
		fi
	fi
done

if [ ! -x $HOMEDIR ]
then
   mkdir $HOMEDIR
   chown $UID $HOMEDIR
   chgrp $GID $HOMEDIR
   chmod 755 $HOMEDIR
fi

if [ ! -x $HOMEDIR/.profile ]
then
   cp /etc/basicprofile $HOMEDIR/.profile
   chown $UID $HOMEDIR/.profile
   chgrp $GID $HOMEDIR/.profile
   chmod 755 $HOMEDIR/.profile
fi
