#!/bin/bash
# Samba-TNG                                              add_unix_user
# --------------------------------------------------------------------

# --------------------------------------------------------------------
# config here

. ./prefs

# --------------------------------------------------------------------
# print usage

if [ "$1" == "" ]; then
        echo "Usage: $(basename $0) <user>"
        exit 1
fi

# --------------------------------------------------------------------
# do some error checking

userexist=`getent passwd|grep -w "$1"`

if [ "$userexist" != "" ]; then
        echo "User already exists!"
        exit 1
fi


nextridhex=`$ldapsearch -D $binddn -w $bindpassword id=root nextrid -LLL|grep nextrid|awk '{print $2}'`
nextriddec=`$perl -e "print hex(\"$nextridhex\")"`

if test "$nextridhex" = ""; then
    echo "error: can not get next rid! (nextridhex)"
    echo "is the ldap server alive ?"
    exit 1
fi

if test "$nextriddec" = ""; then
    echo "error: can not get next rid! (nextriddec)"
    echo "is the ldap server alive ?"
    exit 1
fi

if test "$nextriddec" = "0"; then
    echo "error: nextriddec renturned 0 !"
    echo "possibly a typo in nextriddec= ?"
    exit 1
fi

# --------------------------------------------------------------------
# begin

touch addunixuser_temp.ldif

# ---------------------- addunixuser_temp.ldif -----------------------
echo "dn: uid="$1",ou=People,"$topsuffix >>addunixuser_temp.ldif
echo "uid: "$1 >>addunixuser_temp.ldif
echo "cn: "$1 >>addunixuser_temp.ldif
echo "objectclass: account" >>addunixuser_temp.ldif
echo "objectclass: posixAccount">>addunixuser_temp.ldif
echo "objectclass: top" >>addunixuser_temp.ldif
echo "objectClass: shadowAccount" >>addunixuser_temp.ldif
echo "userPassword: "$1 >>addunixuser_temp.ldif
echo "loginShell: /bin/false" >>addunixuser_temp.ldif
echo "uidNumber: "$nextriddec >>addunixuser_temp.ldif
echo "gidNumber: 100" >>addunixuser_temp.ldif
echo "homeDirectory: /home/$1" >>addunixuser_temp.ldif
echo "gecos: "$1 >>addunixuser_temp.ldif
# ---------------------- addunixuser_temp.ldif -----------------------

$ldapadd -D $binddn -w $bindpassword -f addunixuser_temp.ldif

rm addunixuser_temp.ldif

# --------------------------------------------------------------------
# create home directory and set permissions

if [ -d /home/$1 ] ; then
    echo "directory /home/$1 already present."
    chown $1.users /home/$1
    chmod 750 /home/$1
else
    mkdir /home/$1
    chown $1.users /home/$1
    chmod 750 /home/$1
fi

echo "$0: added unix user $1."

exit 0

# --------------------------------------------------------------------
