#!/bin/sh
### BEGIN INIT INFO
# Provides:          slapd
# Required-Start:    $remote_fs $network $syslog saslauthd
# Required-Stop:     $remote_fs $network $syslog saslauthd
# Default-Start:     2 3 4 5
# Default-Stop:      0 6
# Short-Description: Wrapper for OpenLDAP standalone server 
### END INIT INFO

# Specify path variable
PATH=/sbin:/usr/sbin:/bin:/usr/bin

# Kill me on all errors
set -e

# Stop processing if init.d slapd is not there
SLAPDINIT=/etc/init.d/slapd.tp-conf-ldap-srv
[ -x ${SLAPDINIT} ] || exit 0

# Source the init script configuration
if [ -f "/etc/default/slapd" ]; then
	. /etc/default/slapd
fi

# Load the default location of the slapd config file
if [ -z "$SLAPD_CONF" ]; then
	SLAPD_CONF="/etc/ldap/slapd.conf"
else
	SLAPD_OPTIONS="-f $SLAPD_CONF $SLAPD_OPTIONS"
	SLURPD_OPTIONS="-f $SLAPD_CONF $SLURPD_OPTIONS"
fi

# Stop processing if the config file is not there
if [ ! -r "$SLAPD_CONF" ]; then
  cat <<EOF >&2
No configuration file was found for slapd at $SLAPD_CONF.
If you have moved the slapd configuration file please modify
/etc/default/slapd to reflect this.  If you chose to not
configure slapd during installation then you need to do so
prior to attempting to start slapd.
An example slapd.conf is in /usr/share/slapd
EOF
  exit 0 # Should this be 1?
fi
	
# Find out the name of slapd's pid file
if [ -z "$SLAPD_PIDFILE" ]; then
	SLAPD_PIDFILE=`sed -ne 's/^pidfile[[:space:]]\+\(.\+\)/\1/p' \
		"$SLAPD_CONF"`
fi

# Start the OpenLDAP daemons
start() {
	echo -n "Starting OpenLDAP:"
	trap 'report_failure' 0
	piddir=`dirname "$SLAPD_PIDFILE"`
	[ -d $piddir ] || mkdir -p $piddir
        # Make sure the pidfile directory exists with correct permissions
	[ -z "$SLAPD_USER" ] || chown -R "$SLAPD_USER" "$piddir"
	[ -z "$SLAPD_GROUP" ] || chgrp -R "$SLAPD_GROUP" "$piddir"

	touch ${SLAPD_PIDFILE%.pid}.started
	${SLAPDINIT} start
	trap "-" 0
	echo .
}

# Stop the OpenLDAP daemons
stop() {
	echo -n "Stopping OpenLDAP:"
	trap 'report_failure' 0
	${SLAPDINIT} stop
	rm -f ${SLAPD_PIDFILE%.pid}.started
	trap "-" 0
	echo .
}

case "$1" in
  start)
  	start ;;
  stop)
  	stop ;;
  restart|force-reload)
  	stop
	start
	;;
  *)
  	echo "Usage: $0 {start|stop|restart|force-reload}"
	exit 1
	;;
esac
