#!/bin/sh
### BEGIN INIT INFO
# Provides:          fetch-ldap-cert
# Required-Start:    $local_fs $remote_fs
# Required-Stop:     $local_fs $remote_fs
# Should-Start:      $network apache apache2
# Should-Stop:       $network apache apache2
# Default-Start:     2 3 4 5
# Default-Stop:
# Short-Description: Fetch LDAP SSL public key from the server
# Description:
### 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

do_start() {
    if [ ! -f $CERTFILE ] && grep -q /etc/ldap/ssl/ldap-server-pubkey.pem /etc/ldap/ldap.conf ; then
	[ "$VERBOSE" != no ] && log_action_begin_msg "Fetching LDAP SSL certificate."
        # Fetch using openssl directly from the server
	if echo | openssl s_client -connect ldap:636 > $CERTFILE.new 2>/dev/null ; then
	    # Drop headers and footers, and only store the certificate itself
	    awk '/^-----BEGIN CERTIFICATE-----$/ { yes=1 } yes { print } /^-----END CERTIFICATE-----$/ { yes=0 }' \
		< $CERTFILE.new > $CERTFILE
	    rm $CERTFILE.new
	    [ "$VERBOSE" != no ] && log_action_end_msg 0
	else
	    rm $CERTFILE.new
	    log_action_end_msg 1
	fi
    fi
}

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