#!/bin/bash
#
# ::copy::
# ::maintainer::
#
# launches smbldap-populate with the correct parms
#
CMD=`basename $0`

# (FUNCTIONS)

ku-get-conf()
{
	local var="$1"
	local cmd="jtconf"

	[ "$RUNDIR" == "" ] && cmd="kusa-conf"

	$cmd $var || {
		echo -e "missing declaration of '$var'\n\n" \
		"(must be defined in the kusa config databse)" >&2
		exit 1
	}
}

cleanup()
{
	rm -f $tmp
}



# (MAIN)

[ "`id -u`" != 0 ] && {
	echo "error, you must be root to run this command" >&2
	echo "       (maybe you can use 'sudo')" >&2
	exit 1
}


set -e

firstuid=`ku-get-conf ldap.starting_uid`
admin=`ku-get-conf samba.admin`
admpwd=`ku-get-conf samba.admin_pwd`
guest=`ku-get-conf samba.guest_user`
firstgid=`ku-get-conf samba.first_gid`
firstrid=`ku-get-conf samba.first_rid`

usersgroup=`ku-get-conf ldap.group_users`
usersgid=`ku-get-conf ldap.group_users_gid`


if entry=`getent passwd $guest`
then
	guestuid=`echo "$entry" | cut -d':' -f3`
else
	guestuid=`ku-get-conf samba.guest_uid`
fi

if entry=`getent passwd $admin`
then
	admuid=`echo "$entry" | cut -d':' -f3`
	admgid=`echo "$entry" | cut -d':' -f4`
else
	admuid=`ku-get-conf samba.admin_uid`
	admgid=`ku-get-conf samba.admin_gid`
fi

tmp=`mktemp /tmp/$CMD-XXXXXX` || exit $?

trap "echo '*INTR*'; cleanup ; exit 127" 1 2 3
trap "cleanup" EXIT

echo -e "$admpwd\n$admpwd" | smbldap-populate \
  -u $firstuid \
  -g $firstgid \
  -r $firstrid \
  -a $admin -k $admuid -m $admgid \
  -b $guest -l $guestuid \
  2>$tmp || {
	stat=$?
	echo "ERROR $stat on smbldap-update" >&2
	cat $tmp >&2
	cleanup
	exit $stat
}

# update samba admin settings:
#
# - need to have access to shell
# - add 'users' group
# - add 'Domain Admins' group (512)
#
smbldap-usermod -s "/bin/bash" -G "$usersgroup,512" $admin

# create samba admin home dir if not exists
# (smbldap-populate doesn't do it)
# uses PAM autocreate function to do it, running a null
# command via 'su -'
#
env - su - $admin echo 2>/dev/null || :


echo -e "\n"



# standard users group, is different from wired one?
#
[ $usersgid != 513 ] && {
	echo "  users group $usersgid diffs from wired 513 (Domain Users), updating"
	smbldap-groupmod -a -r $usersgid $usersgroup 2>$tmp || {
		stat=$?
		echo "ERROR $stat on smbldap-groupmod" >&2
		cat $tmp >&2
		cleanup
		exit $stat
	}
}

# sudoers for smbldap commands
#
grep -q "^$admin[ ,	][ ,	]*" /etc/sudoers || {
	echo "  updating /etc/sudoers file for '$admin' user..."
	echo "
# samba domain administrator
# added by __TOOLKIT__ on `date`
#
$admin	ALL=NOPASSWD: /usr/sbin/*smbldap-*
" >> /etc/sudoers || exit $?
}

exit 0
