#! /bin/sh
# Copyright (c) 1997-2000 SuSE GmbH Nuernberg, Germany.
# Copyright (c) 2002 SuSE Linux AG Nuernberg, Germany.
#
# Author: Carsten Hoeger <choeger@suse.de>, 1997-2001
#         Ralf Haferkamp <rhafer@suse.de>, 2002
#
# /etc/init.d/ldap
#
### BEGIN INIT INFO
# Provides:       ldap
# Required-Start: $remote_fs
# Required-Stop:
# Default-Start:  3 5
# Default-Stop:
# Description:    start the OpenLDAP2 Server
### END INIT INFO

# Determine the base and follow a runlevel link name.
base=${0##*/}
link=${base#*[SK][0-9][0-9]}

test -f /etc/sysconfig/openldap && . /etc/sysconfig/openldap

SLAPD_BIN=/usr/lib/openldap/slapd
SLAPD_URLS="ldap:///"

test -x $SLAPD_BIN || exit 5

# Shell functions sourced from /etc/rc.status:
#      rc_check         check and set local and overall rc status
#      rc_status        check and set local and overall rc status
#      rc_status -v     ditto but be verbose in local rc status
#      rc_status -v -r  ditto and clear the local rc status
#      rc_failed        set local and overall rc status to failed
#      rc_failed <num>  set local and overall rc status to <num><num>
#      rc_reset         clear local rc status (overall remains)
#      rc_exit          exit appropriate to overall rc status
. /etc/rc.status

# First reset status of this service
rc_reset

function init_ldap_listener_urls(){
    LDAPI_URL=""
    case "$OPENLDAP_START_LDAPI" in
        [Yy][Ee][Ss])
            LDAPI_URL="ldapi:///"
            SLAPD_URLS="$LDAPI_URL $SLAPD_URLS"
        ;;
    esac
    if [ -n "$OPENLDAP_LDAP_INTERFACES" ]
    then
        SLAPD_URLS="$LDAPI_URL";
        for iface in $OPENLDAP_LDAP_INTERFACES ;do
            SLAPD_URLS="$SLAPD_URLS ldap://$iface/"
        done
    fi
}

function ldaps_check_tls_options(){
    case "$OPENLDAP_START_LDAPS" in
        yes|Yes|YES)
	    if [ -n "$OPENLDAP_LDAPS_INTERFACES" ]
	    then
        	    for iface in $OPENLDAP_LDAPS_INTERFACES ;do
        	    SLAPD_URLS="$SLAPD_URLS ldaps://$iface"
        	    done
	    else
        	    SLAPD_URLS="$SLAPD_URLS ldaps:///"
	    fi
            return 0;
            ;;
        *)
            return 0;
            ;;
    esac
}

function run_db_recover(){
    if [ -x "/usr/bin/db_recover" ]; then
        DIRECTORIES=`grep ^directory /etc/openldap/slapd.conf | awk '{print $2}'`
        echo "Running db_recover for all bdb backends"
        for i in $DIRECTORIES; do
            if [ -f $i/id2entry.bdb ]; then
                db_recover -h $i
            fi
        done
    fi
}

function check_connection(){
	SLAPD_TIMEOUT=10
        START=$( date +%s)
        while [ $(( $( date +%s) - ${START} )) -lt ${SLAPD_TIMEOUT} ]; do
		ldapsearch -x -H "$SLAPD_URLS" -b "" -s base &>/dev/null
                LDAPSEARCH_RC=$?
                if [ ${LDAPSEARCH_RC} -eq 0 ]; then break
                else sleep 1
                fi
        done
}

USER_CMD=""
GROUP_CMD=""
[ ! "x$OPENLDAP_USER" = "x" ] && USER_CMD="-u $OPENLDAP_USER"
[ ! "x$OPENLDAP_GROUP" = "x" ] && GROUP_CMD="-g $OPENLDAP_GROUP"



# Return values acc. to LSB for all commands but status:
# 0 - success
# 1 - generic or unspecified error
# 2 - invalid or excess argument(s)
# 3 - unimplemented feature (e.g. "reload")
# 4 - insufficient privilege
# 5 - program is not installed
# 6 - program is not configured
# 7 - program is not running
# 
# Note that starting an already running service, stopping
# or restarting a not-running service as well as the restart
# with force-reload (in case signalling is not supported) are
# considered a success.

case "$1" in
    start)
        if [ -f /etc/openldap/UPDATE_NEEDED ]; then
            rc_failed 6
            echo "  The configuration of your LDAP server needs to be updated."
            echo "  Please see /usr/share/doc/packages/openldap2/README.update"
            echo "  for details."
            echo "  After the update please remove the file:"
            echo "    /etc/openldap/UPDATE_NEEDED"
            rc_status -v
            exit
        fi
        if [ "$(echo "$OPENLDAP_RUN_DB_RECOVER" | tr 'A-Z' 'a-z')" == "yes" ]; then
            run_db_recover;
        fi

	# chown backend directories if OPENLDAP_CHOWN_DIRS ist set
	if [ "$(echo "$OPENLDAP_CHOWN_DIRS" | tr 'A-Z' 'a-z')" == "yes" ]; then
	    if [ -n "$OPENLDAP_USER" -o -n "$OPENLDAP_GROUP" ]; then
		ldapdir=`grep ^directory /etc/openldap/slapd.conf | awk '{print $2}'`
		# could be more than one
		for n in $ldapdir; do
			[ -d "$n" ] && [ -n "$OPENLDAP_USER" ] && \
				chown -R $OPENLDAP_USER $n 2>/dev/null
			[ -d "$n" ] && [ -n "$OPENLDAP_GROUP" ] && \
				chgrp -R $OPENLDAP_GROUP $n 2>/dev/null
		done
		chgrp $OPENLDAP_GROUP /etc/openldap/slapd.conf 2>/dev/null
		chmod 640 /etc/openldap/slapd.conf 2>/dev/null
		if test -f /usr/lib/sasl2/slapd.conf ; then
		chgrp $OPENLDAP_GROUP /usr/lib/sasl2/slapd.conf 2>/dev/null
		chmod 640 /usr/lib/sasl2/slapd.conf 2>/dev/null
		fi
	    fi
	fi

	case "$OPENLDAP_REGISTER_SLP" in
		[Yy][Ee][Ss])
			SLAPD_SLP_REG=""
		;;
		*)
			SLAPD_SLP_REG="-N"
		;;
	esac

        init_ldap_listener_urls
        ldaps_check_tls_options
        echo -n "Starting ldap-server"
        /sbin/startproc -p /var/run/slapd/slapd.pid $SLAPD_BIN -h "$SLAPD_URLS" $USER_CMD $GROUP_CMD $OPENLDAP_SLAPD_PARAMS $SLAPD_SLP_REG
	# Remember status and be verbose
	rc_status -v
	check_connection
        ;;
    stop)
        echo -n "Shutting down ldap-server"
        /sbin/killproc -TERM -p /var/run/slapd/slapd.pid $SLAPD_BIN
	# Remember status and be verbose
	rc_status -v

        ;;
    try-restart)
	## Stop the service and if this succeeds (i.e. the 
	## service was running before), start it again.
	## Note: try-restart is not (yet) part of LSB (as of 0.7.5)
	$0 status >/dev/null &&  $0 restart

	# Remember status and be quiet
	rc_status
	;;
    restart)
	## Stop the service and regardless of whether it was
	## running or not, start it again.
	$0 stop
	# sometimes slapd needs some time to stop
	sleep 3
	$0 start

	# Remember status and be quiet
	rc_status
        ;;
    force-reload)
	## Signal the daemon to reload its config. Most daemons
	## do this on signal 1 (SIGHUP).
	## If it does not support it, restart.

	#echo -n "Reload ldap server"
	# if it supports it:
	#killproc -HUP $SLAPD_BIN
	#touch /var/run/FOO.pid
	#rc_status -v

	## Otherwise:
	$0 stop; sleep 3;  $0 start
	rc_status
	;;
    reload)
        echo -n "Reload ldap server"

	# If it supports signalling:
	#killproc -HUP $SLAPD_BIN
	#touch /var/run/FOO.pid
	#rc_status -v
	
	## Otherwise if it does not support reload:
	rc_failed 3
	rc_status -v
        ;;
    status)
        echo -n "Checking for service ldap: "
	## Check status with checkproc(8), if process is running
	## checkproc will return with exit status 0.

	# Status has a slightly different for the status command:
	# 0 - service running
	# 1 - service dead, but /var/run/  pid  file exists
	# 2 - service dead, but /var/lock/ lock file exists
	# 3 - service not running

	# NOTE: checkproc returns LSB compliant status values.

        checkproc -p /var/run/slapd/slapd.pid $SLAPD_BIN
	rc_status -v

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