#!/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"

user="$1"
level="$2"
TEMPF="$$_temp"
DIR=`dirname $0`
DIST="$DIR/dist"
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
if [ "`echo $LEVELS | tr ' ' '\n' | grep $level`" != "$level" ]
then
    echo "Level should be one of $LEVELS"
    abort
fi
. /etc/slis/slis.conf
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
    echo "Unknown user $user"
    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=`grep home $TEMPF.ldiff | cut -d ' ' -f 2`
mv $home $home.bak
cp -r $skel $home
cp -r $home.bak/* $home/
rm -rf $home.bak
# fix links
if [ -e "$home/.wine/drive_c/users/01-mini/Bureau" ]
then
    ln -sf $home/Bureau $home/.wine/drive_c/users/01-mini/Bureau 
fi
# fix samba passwd
# TODO: test me
echo "You willbe prompted twice for samba password, please enter the same as for LDAP"
smbpasswd -U $user
# fix Rights
chown -R $uid:lcs-users $home
rm $TEMPF*
