#!/bin/bash
#
# ::copy::
# ::maintainer::
#
# transform a non-samba user to a samba one, using smbldap-usermod
# and passing the correct default settings (can be used to fix
# defaults ad any moment, too)
#

# (FUCNTIONS)

usage()
{
	echo "usage: `basename $0` user" >&2
	exit 1
}

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)


[ "$1" = "" ] && usage
user=$1

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


# retrieve user infos
#
entry=`getent passwd "$user"` || {
	echo "error, user '$user' doesn't exists" >&2
	exit 1
}
gid=`echo "$entry" | cut -d':' -f4`
surname=`echo "$entry" | cut -d':' -f5 | sed -e 's/.* //'`
name=`echo "$entry" | cut -d':' -f5 | sed -e "s/ *$surname//"`
home_drive=`ku-get-conf samba.home_drive`
home_path=`ku-get-conf samba.home_path`
logon_script=`ku-get-conf samba.logon_script`
profile_path=`ku-get-conf samba.profile_path`

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

trap "cleanup ; exit 127" 1 2 3

# group sanity check
#
entry=`ldapsearch -x "(&(gidNumber=$gid)(objectClass=posixGroup))"` || exit $?
echo "$entry" | grep -qi "^sambasid: " || {
	echo "error, the user '$user' has group id '$gid', that is not a Samba one" >&2
	echo "       to fix, run ku-smbldap-populate or manually update the group" >&2
	echo "       using 'smbldap-groupmod -a <groupname>'" >&2
	exit 1
}


# first, try to samba-enable the user (ignore errors)
#
entry=`smbldap-usershow $user` || {
	echo "error, user '$user' is not managed by LDAP" >&2
	exit 1
}
echo -en "  updating user '$user': "

if echo "$entry" | grep -q "sambaSamAccount"
then
	echo -n "(already a samba user) "
	add_flag=
else
	add_flag="-a"
fi

# then fixes default values
#
smbldap-usermod \
  $add_flag \
  -C "$home_path" \
  -D "$home_drive" \
  -E "$logon_script" \
  -F "$profile_path" \
  -N "$name" \
  -S "$surname" \
  $user \
  2>$tmp || {
  	stat=$?
	echo "ERROR $stat on smbldap-usermod" >&2
	cat $tmp >&2
	cleanup
	exit $stat
}

cleanup
echo "done"
exit 0
