#! /bin/sh


domain=$(/sbin/e-smith/config get DomainName)
ldif="/home/e-smith/db/ldap/$domain.ldif"

if [ -e /etc/openldap/ldif ]
then
    old_ldif=$(readlink /etc/openldap/ldif)
    if [ "$old_ldif" != "$ldif" ]
    then
        # The domain name has changed, so we need to delete
        # the old directory contents. We still have the old
        # dump.
        mv -f $old_ldif $ldif
        find /var/lib/ldap -type f | xargs rm -f
    fi
fi

if [ -f /var/lib/ldap/nextid.dbb ]
then
    # We are upgrading from an earlier version which used
    # ldbm backend format. Delete the backend files, and
    # restore from ldif
    find /var/lib/ldap -type f | xargs rm -f
fi

# Set up symlink for ldap dump at shutdown
ln -sf $ldif /etc/openldap/ldif

/sbin/e-smith/expand-template /var/lib/ldap/DB_CONFIG

# Make sure we use the slapd.conf file instead of the new slapd.d
touch /etc/openldap/slapd.d/unused
find /etc/openldap/slapd.d/ -mindepth 1 -maxdepth 1 -not -name unused -exec rm -rf {} \;
/sbin/e-smith/expand-template /etc/openldap/slapd.conf

# Prime directory if required
if [ \! -f /var/lib/ldap/id2entry.bdb ]
then
    if [ -e /etc/openldap/ldif ]
    then
        /sbin/e-smith/ldif-fix -i /etc/openldap/ldif | setuidgid ldap slapadd -c
    else
        /sbin/e-smith/ldif-fix -i /dev/null | setuidgid ldap slapadd -c
    fi
else
    setuidgid ldap /usr/bin/db_recover -v -h /var/lib/ldap
fi

# Make sure all DB files belongs to ldap:ldap
find /var/lib/ldap -not -name DB_CONFIG -exec chown ldap:ldap {} \;

exit 0
