#!/bin/bash

SERV_DIR=$(cd $(dirname $0); pwd)
KAZ_ROOT=$(cd $(dirname $0)/../..; pwd)
. "${KAZ_ROOT}/bin/.commonFunctions.sh"
setKazVars

cd $(dirname $0)
. "${DOCKERS_ENV}"
. "${KAZ_KEY_DIR}/env-${ldapServName}"

checkDockerRunning "${ldapServName}" "LDAP" || exit

printKazMsg "\n  *** Update du LDAP"

LDAP_IP=$(docker inspect -f '{{.NetworkSettings.Networks.ldapNet.IPAddress}}' ldapServ)

BINDDN=cn=${LDAP_ADMIN_USERNAME},${ldap_root}
DC=$(echo ${ldap_root} | cut -d',' -f1 | cut -d'=' -f2)

cp base/acl.ldif.tmpl /tmp/acl.ldif
sed -i -e "s/\$BINDDN/${BINDDN}/g" /tmp/acl.ldif
sed -i -e "s/\$LDAPROOT/${ldap_root}/g" /tmp/acl.ldif

cp base/skeleton.ldif.tmpl /tmp/skeleton.ldif
sed -i -e "s/\$LDAPROOT/${ldap_root}/g" /tmp/skeleton.ldif
sed -i -e "s%\$POSTFIX_PASSWORD%\{CRYPT\}`mkpasswd -m sha512crypt ${LDAP_POSTFIX_PASSWORD}`%g" /tmp/skeleton.ldif
sed -i -e "s%\$LDAPUI_PASSWORD%\{CRYPT\}`mkpasswd -m sha512crypt ${LDAP_LDAPUI_PASSWORD}`%g" /tmp/skeleton.ldif
sed -i -e "s%\$MATTERMOST_PASSWORD%\{CRYPT\}`mkpasswd -m sha512crypt ${LDAP_MATTERMOST_PASSWORD}`%g" /tmp/skeleton.ldif
sed -i -e "s%\$CLOUD_PASSWORD%\{CRYPT\}`mkpasswd -m sha512crypt ${LDAP_CLOUD_PASSWORD}`%g" /tmp/skeleton.ldif
sed -i -e "s%\$MOBILIZON_PASSWORD%\{CRYPT\}`mkpasswd -m sha512crypt ${LDAP_MOBILIZON_PASSWORD}`%g" /tmp/skeleton.ldif
sed -i -e "s%\$MASTODON_PASSWORD%\{CRYPT\}`mkpasswd -m sha512crypt ${LDAP_MASTODON_PASSWORD}`%g" /tmp/skeleton.ldif

cp base/kaz-schema.ldif.tmpl /tmp/kaz-schema.ldif
KAZNUMBER=$(ldapsearch -H ldap://$LDAP_IP -D "cn=${LDAP_CONFIG_ADMIN_USERNAME},cn=config" -w ${LDAP_CONFIG_ADMIN_PASSWORD} -b cn=schema,cn=config | grep "kaz,cn=schema" | head -n1 | cut -d',' -f1 | cut -d'{' -f2 | cut -d'}' -f1)
sed -i -e "s/\$KAZNUMBER/${KAZNUMBER}/g" /tmp/kaz-schema.ldif


ldapmodify -H ldap://$LDAP_IP -D "cn=${LDAP_CONFIG_ADMIN_USERNAME},cn=config" -w ${LDAP_CONFIG_ADMIN_PASSWORD} -f /tmp/acl.ldif
ldapmodify -H ldap://$LDAP_IP -D "cn=${LDAP_CONFIG_ADMIN_USERNAME},cn=config" -w ${LDAP_CONFIG_ADMIN_PASSWORD} -f /tmp/kaz-schema.ldif
ldapadd -c -H ldap://$LDAP_IP -D "${BINDDN}" -w ${LDAP_ADMIN_PASSWORD} -f /tmp/skeleton.ldif
