#!/bin/posix/sh

set -u				# Find undefined variables
set -a				# Export all new variables
. xtutil_scriptInit
set +a

viableUserId()
{
    nisGetAllUsers >$TMP/allUsers
    awk <$TMP/allUsers -F: ' { print $3 } ' >$TMP/allUserIds
    typeset -i uid
    uid=$1
    while true
    do
	egrep "^$uid$" $TMP/allUserIds >/dev/null 2>/dev/null
	if [ $? -ne 0 ]
	then
	    /bin/echo $uid
	    return 0
	fi
	let 'uid=uid+1'
    done
}

# add the "tftp:*:501:10:Trivial FTP user:/usr/tftpdir:/bin/false"
# line to /etc/passwd *before* the + of NIS
addTFTPUser()
{
    [ ! -z "`nisUserEntry $TFTPUSER`" ] && return 0	# Already a user
    uid=`viableUserId 501`			# Get a usable UID
    gid=`nisGetGroupId $TFTPGROUP`
    [ -z "$gid" ] && gid=$TFTPGROUPID

    userLine="$TFTPUSER:*:$uid:$gid:$TFTPGECOS:$TFTPHOME:$TFTPSHELL"
    addLocalUser "$userLine"
}

addLocalUser()
{
    lnum=`egrep -n "^+:" 2>/dev/null | awk -F: ' { print $1 } '`
    if [ -z "$lnum" ]
    then
	/bin/echo "$1"			>>$PASSWD
    else
	let 'lnum0=lnum-1'
	head -$lnum0			>$TMP/passwd
	/bin/echo "$1"			>>$TMP/passwd
	tail -n +$lnum			>>$TMP/passwd
	mv $TMP/passwd $PASSWD
    fi
    return 0
}

if [ "$OS" = "hp9" ]
then
   addTFTPUser				; exitIfNonZero $? 1 "`$NLECHO tftpUser`"

fi

xtutil_AddInetdLine "$TFTPINETDLINE"	; exitIfNonZero $? 1 "`$NLECHO tftpInetdLine`"

markFile $SYSLOG

#Restart inetd

$INETD  $INETD_START_OPT

sleep 3
tailFromMarker

exit 0

