#!/bin/bash
LEVELS="cycle_1 cycle_2 cycle_3 professeur direction"
declare -A SKELS
SKELS[cycle_1]="01-mini"
SKELS[cycle_2]="02-super"
SKELS[cycle_3]="03-maxi"
SKELS[professeur]="prof"
SKELS[direction]="direction"

abort(){
    rm $TEMPF*
    exit 1 
}
usage(){
    echo "Usage $0 username level"
    echo "Transform an existing LDAP user into a Primtux LDAP user"
    echo "Options"
    echo "Level :  {${LEVELS// /|}}"
}

if [ -z "$2" ]
then
    usage
    abort
fi
. /etc/slis/slis.conf
user="$1"
level="$2"
TEMPF="$$_temp"
DIST="`dirname $0`/dist"
set -x
# Check for LDAP group Primtux
if [ -z "ldapsearch -x cn=Primtux | grep numEntries" ]
then
    # insert primtux group
    sed -e "s/BASE/$LDAP_BASE_DN/" $DIST/primtux.ldiff > $TEMPF.ldiff
    ldapadd -x -D "cn=$LDAP_ADMIN_RDN,$LDAP_BASE_DN" -w $LDAP_ADMIN_PW -f $TEMPF.ldiff
fi
ldapsearch -x -LLL uid=$user > $TEMPF.ldiff
if [ ! -s $TEMPF.ldiff ]
then
    abort
fi
# Check for UID => 1000 and update if required
uid=`grep uidNumber $TEMPF.ldiff | cut -d ' ' -f 2`
if [ $uid -eq 1000 ]
then
    # Change UID
    newuid=$(( `slapcat | grep "uidNumber: 10.." | cut -d ' ' -f 2 | sort -nu | tail -n 1`+1))
    # prepare ldiff file
    grep "^dn" $TEMPF.ldiff > $TEMPF.1.ldiff
    echo -e "changetype: modify\nreplace: uidNumber\nuidNumber: $newuid" >> $TEMPF.1.ldiff
    # run ldapmodify
    ldapmodify -x -D "cn=$LDAP_ADMIN_RDN,$LDAP_BASE_DN" -w $LDAP_ADMIN_PW -f $TEMPF.1.ldiff
    uid=$newuid
fi
# Add Primtux to user group
echo -e "dn: cn=Primtux,ou=Groups,$LDAP_BASE_DN\nchangetype: modify\nadd: memberUid\nmemberUid: $user" > $TEMPF.1.ldiff
ldapmodify -x -D "cn=$LDAP_ADMIN_RDN,$LDAP_BASE_DN" -w $LDAP_ADMIN_PW -f $TEMPF.1.ldiff
# Retrieve files from skels
skel="$DIR/skels/${SKELS[$level]}"
home=`$TEMPF.ldiff | cut -d ' ' -f 2`
echo mv $home $home.bak
echo cp -r $skel $home
echo cp -r $home.bak/* $home/
echo rm -rf $home
# fix links
echo ln -sf $home/.wine/drive_c/users/01-mini/Bureau $home/Bureau
# fix Rights
echo chown -R $uid: $home
# fix samba passwd
# TODO: test me
smbpasswd -w $LDAP_ADMIN_PW -n $user
rm $$.ldif
