#!/bin/bash
DIR=`dirname $0`

usage(){
    echo "Usage $0 names.txt"
    echo "Reads a list of name corresponding to some ldap users"
    echo "and run $DIR/create_primtux_user.sh on each of them"
}

if [ -z "$1" ]
then
    usage
    exit 1
fi

if [ ! -f "$1" ]
then
    echo "$1 is not a file"
    usage
    exit 1
fi

rm -f uids.txt
scriptbinpath="/usr/share/lcs/sbin"
. /etc/slis/slis.conf

if [ ! -x $scriptbinpath/userAdd.pl ]
then
    echo "Critical error : $scriptbinpath/userAdd.pl does not exist or is not executable"
    exit 1
fi

while read first last level gender categorie
do
    echo "Creating user for $first $last"
    uid=`ldapsearch -x cn="$first $last" | grep "^uid:" | cut -d ' ' -f 2`
    if [ -z "$uid" ]
    then
        $scriptbinpath/userAdd.pl $first $last "xxx" "" $gender $categorie
    else
        echo "Not recreating user $uid"
    fi
    uid=`ldapsearch -x cn="$first $last" | grep "^uid:" | cut -d ' ' -f 2`
    echo "found uid '$uid'"
    if [ -z "$uid" ]
    then
    	KO="$KO $uid"
        echo "Failed to create user for $first $last"
        continue
    fi
    $DIR/create_primtux_user.sh $uid $level
    # set initial password
    echo "dn: uid=$uid,ou=People,$LDAP_BASE_DN" > $$.ldiff
    echo "changetype: modify" >> $$.ldiff
    echo "replace: userPassword" >> $$.ldiff
    echo "userPassword: $uid" >> $$.ldiff
    ldapmodify -x -D "cn=$LDAP_ADMIN_RDN,$LDAP_BASE_DN" -w $LDAP_ADMIN_PW -f $$.ldiff
    rm $$.ldiff
    echo -e "$uid\n$uid" | smbpasswd -s -U $uid
    echo $uid >> uids.txt
    echo "Done creating $uid"
    OK="$OK $uid"
done < $1
echo "The following users where correctly created"
echo -e "\t$OK"
if [ ! -z $KO ]
then
    echo "Some errors where encountered while creating the following users :"
    echo -e "\t$KO"
fi
