#!/bin/sh
#
# Filename: addbbsuser
# Purpose:	add a new bbs user to the system
# 

# get user info

loginid=$1       #  login ID
fullname=$2      #  Users full name
logshell=$3		# login shell 

bbsgroup=`fgrep bbsuser /etc/group | cut -f3 -d":"`

if  [ "$bbsgroup" = "" ]
then
	echo "bbsuser group not found in /etc/group"
	exit 1
fi

if [ $# -ne 3 ]
then
	echo "USAGE: $0 <Login name> <\"Users full name\"> <Login Shell>"
	exit 1
fi


#	check if the length of input is longer than 8

length=`echo $loginid | wc -c`
if [ "$length" -gt "9" ]
then 
	echo "Login name can not be longer than eight characters."
	exit 1
fi

#	check if login name already exists

loginexists=`grep "^$loginid:" /etc/passwd` 
if [ "$loginexists" != "" ]
then
	echo "$loginid already exists." 
	exit 1
fi

# check full name for illegal chars

echo "$fullname" | grep "[^[0-9]a-z A-Z.]" > /dev/null
if [ "$?" -eq "0" ]
then 
	echo "The full name contains illegal characters." 
	exit 1
fi

# chop characters in full name over 25

newfull=`echo $fullname | cut -c1-25`
fullname=$newfull

#	find the highest user id (should be the last user)

lastid=`cat /etc/passwd | grep -v nobody | cut -f3 -d":" | sort -n | tail -1 | uniq` 
nextid=`echo $lastid | awk "{ print ++x }" x=$lastid -`
if [ "$nextid" -ge 50000 ] 
then
	echo highest id exceeded.
	exit 1
fi

# create a home directory based on first initial
firinit=`echo $loginid | cut -c1`
logdir=`echo $BBSDIR/users/$firinit/$loginid `
if [ -d "$logdir" ]
then
	echo "$logdir directory already exists. Choose another HOME directory."
fi

#
#	Echo entry into /etc/passwd
#

/bbs/bin/anu $loginid "$fullname" $logdir $bbsgroup $nextid

# give them both a .profile and a .login

if [ -r /etc/stdlogin ]
then
		cp /etc/stdprofile ${logdir}/.profile
		chmod 644 ${logdir}/.profile
		chown ${loginid} ${logdir}/.profile
		cp /etc/stdlogin ${logdir}/.login
		chmod 644 ${logdir}/.login
		chown ${loginid} ${logdir}/.login
		cp /etc/stdcshrc ${logdir}/.cshrc
		chmod 644 ${logdir}/.cshrc
		chown ${loginid} ${logdir}/.cshrc
fi

