#!/bin/bash

set -e

if [ "$1" = 'reconfigure' ]; then
    exit
fi

if [ "$(CreoleGet ad_server_role)" = 'membre' ] || [ "$(CreoleGet ad_additional_dc)" = 'oui' ]; then
    exit
fi

function updateSchemaDN()
{
   STR=${1}
   DN=${2}
   FILE=${3}

   sed -i -e "s/${STR}/${DN}/g" ${FILE}
   return ${?}
}

DN="$(CreoleGet base_dn)"
BASEDN="CN=Schema,CN=Configuration,${DN}"

RETURNED=$(ldbsearch --option="dsdb:schema update allowed"=true -H /var/lib/samba/private/sam.ldb -b $BASEDN CN=ENTPersonAutresPrenoms CN | grep returned)

if [ "$RETURNED" = "# returned 0 records" ]; then
    # Import schema
    SCHEMAS="samba.schema eole.schema eoleshare.schema radius.schema ent.schema"
    PRIVATE_DIR=/etc/eole/private
    PASSWORD_FILE="${PRIVATE_DIR}/eole-seth-education.password"
    USER='eole-seth-education'

    user_exists() {
        local username="${1}"
        $CONTAINER_EXEC samba-tool user show "${username}" > /dev/null 2>&1
    }

    for schema in $SCHEMAS
    do
	updateSchemaDN "{DNCONFIG}" "${DN}" /etc/ldap/schema/eole/${schema}.ldif
	if [[ $? -ne 0 ]]
	then
           echo "Error updating DN for ${schema}"
           break
        fi
        ldbmodify -H /var/lib/samba/private/sam.ldb /etc/ldap/schema/eole/${schema}.ldif --option="dsdb:schema update allowed"=true
	if [[ $? -ne 0 ]]
	then
           echo "Error updating Schema ${schema} !!"
           break
	fi
    done

    ldbadd -H /var/lib/samba/private/sam.ldb /var/lib/eole/00_seth.ldif
    ldbmodify --option="dsdb:schema update allowed"=true -H /var/lib/samba/private/sam.ldb /var/lib/eole/01_seth_index.ldif
    if ! user_exists $USER
    then
        MANAGER_PASSWORD=$(cat "${PASSWORD_FILE}")

        echo "Ajout du compte de jonction au domaine '$USER'... "
        $CONTAINER_EXEC samba-tool user create --random-password $USER

        echo "Mise en conformité de l’utilisateur '$USER'... "
        $CONTAINER_EXEC samba-tool user setexpiry $USER --noexpiry
        $CONTAINER_EXEC samba-tool group addmembers 'Domain Admins' $USER
        $CONTAINER_EXEC samba-tool user setpassword $USER --newpassword="${MANAGER_PASSWORD}"
    fi
    if [ "$(CreoleGet aaf_file_format none)" = 'none' ]; then
        /usr/share/eole/backend/creation-groupe.py -g professeurs -t Groupe
        /usr/share/eole/backend/creation-groupe.py -g eleves -t Groupe
        /usr/share/eole/backend/creation-groupe.py -g administratifs -t Groupe
        ldbmodify -H /var/lib/samba/private/sam.ldb /var/lib/eole/02_scribe.ldif
    fi
fi

exit 0
