#!/bin/sh
#   Shell script to facilitate adding usernames to a .htpasswd file
#      for authorized users - starts htpasswd program at end
#   June 14, 1995
#   Christine L. Hammond
#
# Get directory for updating from command line
#
echo "giveauth program - optional arg is directory where passwd file lives"
defdir="/usr/local/share/etc/notok/arabian"
supportdir="/usr/local/httpddir/support"

if test "${1}"
then
   wheredir=$1
   echo "Using the directory indicated: ${wheredir}"
else
   echo "Using the default directory (for ArabianPIs) "
   wheredir=$defdir
fi

# Get username to add, exit if none entered

useris=""
 echo ""
 echo -n "Enter new username (PI lastname): "
 read user

 if test "${user}"
 then
    useris=y
 else
    exit 5
 fi

# Get the group for the username

again=yes
while test $again
do
    echo -n "What group should this user go into [ PIs ] ? "
    read groupname

# Make sure that the group exists
    gis=""
    if test $groupname
    then
       echo ""
    else
       groupname=PIs
    fi

    gis=`grep "^$groupname:" ${wheredir}/.group | awk -F: '{print $1}' `
    if test $gis
    then 
       again=""
    else
	echo ""
	echo "  Unknown group: $groupname."
	echo "Known groups are:"
	/bin/awk -F: '{print $1}' ${wheredir}/.group | pr -t -l1 -4
        echo -n "Please add group $groupname to the .group file and try again "
    fi
done

if test $gis
    then

#	Add the user to group as it is specified 

	grep "^${groupname}:" ${wheredir}/.group | grep "$user" > /dev/null
	if test $? -eq 0
	then 
	    echo ""
	    echo "  User $user is already a member of group $groupname."
	else
	    rm -f /tmp/group /tmp/groupsep /tmp/groupname /tmp/groupitems /tmp/sortitems /tmp/newgroup /tmp/almostgroup > /dev/null
# work on group file in /tmp
	    cp ${wheredir}/.group /tmp/group
# separate all usernames to one-per-line
            tr -cs A-Za-z':' '\012' </tmp/group >/tmp/groupsep
# split off the group name  ** assumes one group per file **
            head -1 /tmp/groupsep >/tmp/groupname
# split out the names 
            tail +2 /tmp/groupsep >/tmp/groupitems
# add new username
            echo ${user} >> /tmp/groupitems
# sort the new list
            sort /tmp/groupitems > /tmp/sortitems
# put the head back on
            cat /tmp/groupname /tmp/sortitems >/tmp/newgroup
# and then remove the newlines so that HTTP likes the file
            tr '\012' ' ' </tmp/newgroup > /tmp/almostgroup
# passwording will work only if line is ended with nl (or maybe null)
            cat /tmp/almostgroup ${supportdir}/nl >${wheredir}/.group
	fi
    fi

# Add/Change the user's password entry

# Start the htpasswd program and exit
echo ""
${supportdir}/htpasswd ${wheredir}/.htpasswd ${user}
