#!/bin/sh
### BEGIN INIT INFO
# Provides:          fetch-ldap-cert
# Required-Start:    $local_fs $remote_fs
# Required-Stop:     $local_fs $remote_fs
# Should-Start:      $network $syslog $named slapd
# Default-Start:     2 3 4 5
# Default-Stop:
# Short-Description: Fetch LDAP SSL public key from the server
# Description:
#   Start before krb5-kdc to give slapd time to become operational
#   before krb5-kdc try to connect to the LDAP server as a workaround
#   for #589915.
# X-Start-Before:    isc-dhcp-server krb5-kdc nslcd
### END INIT INFO
#
# Author: Petter Reinholdtsen <pere@hungry.com>
# Date:   2007-06-09

set -e

. /lib/lsb/init-functions

CERTFILE=/etc/ldap/ssl/ldap-server-pubkey.pem

# Workaround for #585966, give pdns time to become operational
# This workaround should be removed early in the jessie+1 development
# cycle. it's probably not needed now that pdns is gone, but too
# risky to remove so close before the freeze
sleep 2

do_start() {
    # Locate LDAP server
    LDAPSERVER=$(debian-edu-ldapserver)

    ERROR=false
    if [ ! -f $CERTFILE ] && [ -f /etc/ldap/ldap.conf ] &&
       grep -q /etc/ldap/ssl/ldap-server-pubkey.pem /etc/ldap/ldap.conf ; then
	if [ -z "$LDAPSERVER" ] ; then
	    msg="Failed to locate LDAP server"
	    log_action_begin_msg "$msg"
	    log_action_end_msg 1
	    logger -t fetch-ldap-cert "$msg."
	    return 1
	fi
	[ "$VERBOSE" != no ] && log_action_begin_msg "Fetching LDAP SSL certificate."
	ldap-server-getcert $LDAPSERVER > $CERTFILE.new
	chmod 644 $CERTFILE.new
	if test -s $CERTFILE.new ; then
	    mv $CERTFILE.new $CERTFILE
	    [ "$VERBOSE" != no ] && log_action_end_msg 0
	    logger -t fetch-ldap-cert "Fetched LDAP SSL certificate from $LDAPSERVER."
	else
	    rm $CERTFILE.new
	    log_action_end_msg 1
	    logger -t fetch-ldap-cert "Failed to fetch LDAP SSL certificate from $LDAPSERVER."
	    ERROR=true
	fi
    fi
    if [ -d /opt/ltsp ] ; then
	for ltsp_chroot in `find /opt/ltsp/ -mindepth 1 -maxdepth 1 -type d`; do
	    if [ ! -f $ltsp_chroot$CERTFILE ] && [ -f $ltsp_chroot/etc/ldap/ldap.conf ] &&
		grep -q /etc/ldap/ssl/ldap-server-pubkey.pem $ltsp_chroot/etc/ldap/ldap.conf ; then
		[ "$VERBOSE" != no ] && 
		log_action_begin_msg "Copying LDAP SSL certificate to ltsp-chroot $ltsp_chroot "
		if test -s $CERTFILE; then
		    cp $CERTFILE $ltsp_chroot$CERTFILE
		    chmod 644 $ltsp_chroot$CERTFILE
		    [ "$VERBOSE" != no ] && log_action_end_msg 0
		else
		    log_action_end_msg 1
		    ERROR=true
		fi
	    fi
	done
    fi
    if $ERROR; then
	return 1
    fi
}

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