#!/bin/bash
set -e

NAME="OPENLDAP"
SLAPD_CONFIG=${SLAPD_CONFIG:-"/etc/openldap/slapd.d/cn=config"}
SLAPD_DEBUG=${SLAPD_DEBUG:-0}

function stop {
	echo "Stopping ${NAME}"
	kill $(pidof slapd)
}

function mp() {
        set +e
        mountpoint -q $1
        local mp=$?
        set -e
	return ${mp}
}

trap 'stop' SIGTERM

if [ -z "$@" ]; then
	SLAPD_URLS="ldapi:/// ldap:/// ldaps:///"
	SLAPD_OPTIONS="-d ${SLAPD_DEBUG}"

	# If /etc/openldap is an external mount point
	if mp ${SLAPD_CONFIG}; then
		echo "* ${SLAPD_CONFIG} is mounted, checking for existing config"

		if [ -f ${SLAPD_CONFIG}/olcDatabase=\{0\}config.ldif ]; then
			echo "= ${SLAPD_CONFIG} existing configuration detected, aborting..."
		else
			echo "- ${SLAPD_CONFIG} populating default configuration"
			cp -pr ${SLAPD_CONFIG}.orig/* ${SLAPD_CONFIG}
		fi
	fi

	[ -x /usr/sbin/slapd ] && /usr/sbin/slapd -u ldap -h "${SLAPD_URLS}" $SLAPD_OPTIONS &
	wait
else
	exec $@
fi