#!/bin/bash

LDAP_USER=$(grep -E "ldap.authdn=" /opt/rudder/etc/rudder-web.properties |cut -d "=" -f 2-)
LDAP_PASSWORD=$(grep -E "ldap.authpw=" /opt/rudder/etc/rudder-web.properties |cut -d "=" -f 2-)

# Look for rudder. prefixed variables in the system Directives
LDAP_SYSVAR_NOT_PREFIXED=$(/opt/rudder/bin/ldapsearch -H ldap://localhost -x -w "${LDAP_PASSWORD}" -D "${LDAP_USER}" -b "directiveId=common-root,activeTechniqueId=common,techniqueCategoryId=Rudder Internal,techniqueCategoryId=Active Techniques,ou=Rudder,cn=rudder-configuration" -LLL directiveVariable | grep -E '^directiveVariable: [A-Z0-9]+\[[0-9]+\]:\$\{rudder\.' | wc -l)

# If no variables match, it means the migration has not yet be done
if [ ${LDAP_SYSVAR_NOT_PREFIXED} -eq 0 ]; then

# Mettre ça dans une fonction qui prend en param base et filtre pour pouvoir faire 2 et 3 sur bug

	# Build LDIF with interesting values
	/opt/rudder/bin/ldapsearch -H ldap://localhost -x -w "${LDAP_PASSWORD}" -D "${LDAP_USER}" -b "techniqueCategoryId=Active Techniques,ou=Rudder,cn=rudder-configuration" -LLL '(&(directiveVariable=*)(!(techniqueCategoryId=Rudder Internal))(!(techniqueCategoryId:dn:=Rudder Internal)))' directiveVariable| perl -p0e 's/\n //g'|while read line
	do
		if [[ $line =~ ^dn: ]]; then
			ldif="$line\nchangetype: modify"
			needmodification=false
			continue
		elif [[ $line =~ ^directiveVariable ]]; then
			if grep -E '^directiveVariable: [A-Z0-9]+\[[0-9]+\]:\$\{'; then
				needmodification=true
				newline="" # Un truc qui édite la ligne avec sed pour avoir les bonnes variables
				ldif="$ldif\ndelete: $line\nadd: $newline"
			fi
		elif [ $line == "" ]; then
			# Fin d'entree
			if [ "$needmodification" == "true" ]; then
				echo "$ldif\n\n" # | /opt/rudder/bin/ldapmodify -H ldap://localhost -x -w "${LDAP_PASSWORD}" -D ${LDAP_USER} >/dev/null
			fi
		fi
	done

	exit

	# Edit it to match the wanted ones, and insert the whole LDIF
	sed -i 's/${/${rudder./' ${VARUPDATE_TMPFILE}
#	/opt/rudder/bin/ldapmodify -H ldap://localhost -x -w "${LDAP_PASSWORD}" -D ${LDAP_USER} -f ${VARUPDATE_TMPFILE} >/dev/null 2>&1

	/opt/rudder/bin/ldapsearch -H ldap://localhost -x -w "${LDAP_PASSWORD}" -D "${LDAP_USER}" -b "directiveId=common-root,activeTechniqueId=common,techniqueCategoryId=Rudder Internal,techniqueCategoryId=Active Techniques,ou=Rudder,cn=rudder-configuration" -LLL directiveVariable|sed '0,/directiveVariable:/s//changetype: modify\nreplace: directiveVariable\ndirectiveVariable:/' > ${VARUPDATE_TMPFILE}

	# Clean the mess and exit the if
	rm -f ${VARUPDATE_TMPFILE}
        echo "Some old format variables were updated"
fi
