#!/bin/bash

option=$1
container_path_fichier=$(CreoleGet container_path_fichier)

CHROOT=''
[ -n "$container_path_fichier" ] && CHROOT="chroot $container_path_fichier"

$CHROOT id admin &>/dev/null
if [ $? -ne 0 ]
then
    # rechargement de la configuration nscd (#5279 & #5206)
    CreoleService -c fichier nscd restart
    # pré-activation du shell (#4231)
    if [ -n "$(CreoleGet interface_client_ltsp 2>/dev/null)" -o "$(CreoleGet activer_nfs 2>/dev/null)" = "oui" ];then
        shell="-s"
    else
        shell=""
    fi
    # ajout utilisateur admin
    if [ -f /usr/share/eole/backend/creation-prof.py ];then
        # SCRIBE
        /usr/share/eole/backend/creation-prof.py -u admin -m admin -p admin -f admin -M 'internet' -z 1 -q 0 -x 1 $shell
        [ $? -ne 0 ] && [ "$(CreoleGet activer_ad non])" != 'oui' ] && exit 1
    else
        # HORUS
        python -c "from horus import backend; backend.add_user('admin', 'DomainUsers', ['DomainAdmins', 'PrintOperators'], shell='$shell')"
        if [ -L /data ];then
            python -c """from horus.backend import add_group, add_share
add_group('applidos')
add_group('minedu')
add_share('applidos', 'applidos', filepath='/data/applidos', sticky=True, sync=False, drive='F:')
add_share('minedu', 'minedu', filepath='/data/minedu', sticky=True, sync=False, drive='X:', model='minedu')
"""
        fi
    fi
    if [ "$option" = "instance" ]; then
        echo ""
        echo "#######################################################"
        echo "# Changement du mot de passe de l'utilisateur \"admin\" #"
        echo "#######################################################"
        res=1
        i=0
        while [ "$res" -ne 0 ]
        do
	    i=$((i+1))
	    [ $i = 10 ] && echo "erreur au changement de mot de passe de admin" && exit 1
            $CHROOT /usr/sbin/smbldap-passwd admin
            res=$?
        done
    else
        # le mot de passe doit être changé à la prochaine connexion
    	$CHROOT /usr/bin/net sam set pwdmustchangenow admin yes &>/dev/null
    	tput setaf 3; echo -n "L'utilisateur "
    	tput smso; echo -n admin; tput rmso
    	tput setaf 3; echo -n " a été re-créé avec le mot de passe "
    	tput setaf 8; echo "admin"
    	tput setaf 3; echo "Le système demandera son changement à la prochaine ouverture de session"
    	tput sgr0
    fi
fi

echo -e "\n## Génération de la configuration Samba ##"
/usr/share/eole/sbin/synchro_file.py norestart

# Application des acls sur minedu & applidos si nécessaire (#7576 #5279)
for grp in "minedu" "applidos";do
    dir=/data/$grp
    if [ -d $dir ];then
        getfacl $dir 2>/dev/null | grep -v "^#" | grep -q $grp
        if [ $? -ne 0 ];then
            echo "Correction des ACL sur $dir"
            chgrp $grp $dir
            setfacl -PRm g:$grp:rwx $dir
            setfacl -dPRm g:$grp:rwx $dir
        fi
    fi
done

exit 0
