#! /bin/sh

exec 2>&1

./control/1

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

if [ -e ldif ]
then
    old_ldif=$(readlink 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 ./ldif

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

# If the ldif dump is empty it's sme8beta: init ldap
[ -s "$ldif" ] || rm -f /var/lib/ldap/id2entry.bdb

# Prime directory if required
if [ \! -f /var/lib/ldap/id2entry.bdb ]
then
    if [ -e ldif ]
    then
        ./ldif-fix -i ldif | setuidgid ldap slapadd -c
    else
        ./ldif-fix -i /dev/null | setuidgid ldap slapadd -c
    fi
fi

loglevel=$(/sbin/e-smith/config getprop ldap LogLevel || echo 256)

# Now run daemon
exec /usr/sbin/slapd -4 -u ldap -d $loglevel -s 0 -h "ldap:/// ldaps:/// ldapi:///"
