#!/bin/bash

# Copyright (C) 2018  Tetras Libre <Contact@Tetras-Libre.fr>
# Author: Beniamine, David <David.Beniamine@Tetras-Libre.fr>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

DIR=`dirname $0`

usage(){
    echo "Usage $0 users.txt"
    echo "Reads a list of users and create them"
    echo "then run $DIR/create_primtux_user.sh on each of them with the apropriate level"
}

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