#!/bin/csh
#
# smbadduser - Written by Mike Zakharoff
#
# * Sun Aug 6 2000 Philipp Knirsch <pknirsch@redhat.com>
# - Bugfix to change file location from /etc to /etc/samba and to use
#   smbpasswd -a to add the user entry to the smbpasswd file in case it didn't
#   exist before.
#

unalias *
set path = ($path)

set smbpasswd = /etc/samba/smbpasswd
set user_map  = /etc/samba/smbusers
#
# Set to site specific passwd command
#
set passwd    = "cat /etc/passwd"
#set passwd    = "niscat passwd.org_dir"
#set passwd    = "ypcat passwd"

set line = "----------------------------------------------------------"
if ($#argv == 0) then
	echo $line
	echo "Written: Mike Zakharoff email: michael.j.zakharoff@boeing.com"
	echo ""
	echo "   1) Updates $smbpasswd"
	echo "   2) Updates $user_map"
	echo "   3) Executes smbpasswd for each new user"
	echo ""
	echo "smbadduser unixid:ntid unixid:ntid ..."
	echo ""
	echo "Example: smbadduser zak:zakharoffm johns:smithj"
	echo $line
	exit 1
endif

touch $smbpasswd $user_map
set new  = ()
foreach one ($argv)
	echo $one | grep ':' >& /dev/null
	if ($status != 0) then
		echo "ERROR: Must use unixid:ntid like -> zak:zakharoffm"
		continue
	endif
	set unix = `echo $one | awk -F: '{print $1}'`
	set ntid = `echo $one | awk -F: '{print $2}'`

	set usr = `eval $passwd | awk -F: '$1==USR {print $1}' USR=$unix`
	if ($#usr != 1) then
		echo "ERROR: $unix Not in passwd database SKIPPING..."
		continue
	endif

	# Fix 8/7/2000 Phil Knirsch: Removed the smbpasswd stuff here and fixed
	# the way the usermap gets updated as that one was really wrong: If a
	# user was added twice the usermap would contain 2 entries! We now
	# first select the existing entry, remove it from the usermap and add
	# a new one with the new ntid. If something goes wrong the new entry
	# will as before simply be added to the file (for manual fixing later).
        set usr = `eval cat $user_map | awk -F= '{if(match($1, USR" *") != 0) print $2}' USR=$unix`

	if ($unix != $ntid) then
		echo "Adding: {$unix = $usr $ntid} to $user_map"
                cat $user_map | sed /"$unix.*"/d > $user_map.new
                if (-e $user_map.new) then
                    cp $user_map.new $user_map
                endif
                rm $user_map.new
		echo "$unix = $usr $ntid" >> $user_map
	endif
	set new = ($new $unix)
end

#
# Enter password for new users
#
foreach one ($new)
	echo $line
	echo "ENTER password for $one"

        # Fix Phil Knirsch 8/6/2000: Use the -a option to create the user
        # entry in case it didn't exist before. This way we get rid of the
        # file format dependent awk replacement in the previous version.
	smbpasswd -a $one
end
