#!/bin/sh

# Echo error
function error()
{
    echo "ERROR:" $* >&2
}

# Abort script execution
function abort()
{
    error "${1:-ABORTED.}"
    exit -1
}

# VZL defines
. ${VZA_TMPDIR}/opt/vzagent/install/etc/vzl_defines || abort "Failed to include ${VZA_TMPDIR}/opt/vzagent/install/etc/vzl_defines"
. ${VZA_TMPDIR}/opt/vzagent/install/etc/vzl_functions || abort "Failed to include ${VZA_TMPDIR}/opt/vzagent/install/etc/vzl_functions"

####################
#  Defines
####################

LDAP_SLAPD_CONFIG="${LDAP_ROOT}/etc/openldap/slapd.conf"

####################
#  Functions
####################

# echo usage
function usage() {
	cat 1>&2 << EOF
Usage: $PROGNAME <scheme-file>|<data-file> [<scheme-file>|<data-file> ...]
EOF
	exit 1
}

# restore VZL_LDAP_USER password from pstorage
function getLdapRootPassword()
{
	cat ${LDAP_ROOT}/${VZLCORE_PSTORAGE_DIR}/${VZL_LDAP_USER} | \
		${VZLCORE_BIN_DIR}/base64 -d | grep -v ${VZL_LDAP_USER}
}

# restore EID from pstorage
function getEID()
{
    cat ${LDAP_ROOT}/${VZLCORE_ETC_DIR}/eid
}

# load new data to LDAP 
function ldapLoadData()
{
	local ldapPassword=`getLdapRootPassword`
    local EID=`getEID`
	local schemePath=$1
    
    echo "# Adding $schemePath to LDAP"

	sed -e "s#cn=VZCP,dc=VZL#cn=VZCP,ou=${EID},dc=VZL#i" ${schemePath} | $LDAP_LDAPADD -c -x -w "${ldapPassword}" -D "cn=${VZL_LDAP_USER},dc=VZL" || \
    sed -e "s#cn=VZCP,dc=VZL#cn=VZCP,ou=${EID},dc=VZL#i" ${schemePath} | $LDAP_LDAPMODIFY -c -x -w "${ldapPassword}" -D "cn=${VZL_LDAP_USER},dc=VZL" || \
    abort "Failed to add $schemePath to LDAP"
}

# add new scheme to LDAP
function ldapAddScheme()
{
	set -e
	
	local scheme="$1"
    
	echo "# Adding scheme $scheme"
	
	if [ -n "${LDAP_FEDORA_DS}" ] ; then
		local name=`basename $scheme`
		ln -s $scheme ${LDAP_FEDORA_DS_ROOT}/config/schema/80.${name}.ldif
	else
		local tmpfile=`mktemp ${LDAP_SLAPD_CONFIG}.XXXXXX`
		trap "rm -f $tmpfile" 0
		grep -v $scheme ${LDAP_SLAPD_CONFIG} > $tmpfile
		echo "include $scheme" >> $tmpfile
		cp -f $tmpfile ${LDAP_SLAPD_CONFIG}
		rm -f $tmpfile
	fi
	set +e
}

# restart LDAP
function ldapRestart()
{
	${LDAP_INITSCRIPT} restart
}

####################
#  Main part
####################
[ -n "$1" ] || usage

# commit new schema files (*.schema)
new_schema=false
for i in "$@"; do
	case "$i" in *.schema)
		ldapAddScheme $i
		new_schema=true
		;;
	esac
done

# restart LDAP
if $new_schema; then
	ldapRestart
	ldap_wait_start
fi

# commit new data files (*.ldif)
for i in "$@"; do
	case "$i" in *.ldif)
		ldapLoadData "$i"
		;;
	esac
done

