#!/bin/sh -e
#
# Test if the LDAP server is working.
# $Id: ldap-server 74294 2011-11-27 18:03:18Z pere $

if test -r /etc/debian-edu/config ; then
    . /etc/debian-edu/config
fi

# Only Main-Server should use LDAP
if echo "$PROFILE" | grep -q Main-Server ; then
    :
else
    exit 0
fi

if [ -f /etc/ldap/slapd.conf ] ; then
    if grep -q '^security.* simple_bind=128' /etc/ldap/slapd.conf ; then
	echo "success: $0: LDAP not requiring encryption to bind"
    else
	echo "error: $0: LDAP not requiring encryption to bind"
    fi
else
    echo "error: $0: /etc/ldap/slapd.conf is missing.  Is slapd installed?"
    exit 1
fi

if pidof slapd > /dev/null ; then
    echo "success: $0: slapd is running."
else
    echo "error: $0: slapd is not running."
    exit 1
fi

RESULT=0

for port in ldap ldaps ; do
    proto=tcp

    if netstat -a --numeric-hosts 2>&1 | grep ":$port " | grep -q "^$proto" ; then
        echo "success: $0: slapd server is listening on $port/$proto."
    else
        echo "error: $0: slapd server is not listening on $port/$proto."
        RESULT=1
    fi
done

if [ -x /usr/sbin/slapcat ] ; then
    slapcat | sed "s%^%info: $0: slapcat: %"
else
    echo "error: $0: Unable to find /usr/sbin/slapcat"
    RESULT=1
fi

if [ -f /etc/ldap/ssl/slapd.pem ] ; then
    openssl verify  /etc/ldap/ssl/slapd.pem | 
	  sed "s%^%info: $0: slapd.pem: %"
else
    echo "error: Missing /etc/ldap/ssl/slapd.pem"
    RESULT=1
fi

# If the client certificate exist, verify that it is identical to the
# server certificate.  If not, it was probably downloaded from the
# wrong LDAP server.
if [ -f /etc/ldap/ssl/ldap-server-pubkey.pem ] ; then
    if awk '/^-----BEGIN CERTIFICATE-----$/ { yes=1 }
            yes { print }
           /^-----END CERTIFICATE-----$/ { yes=0 }' /etc/ldap/ssl/slapd.pem |
	cmp -s /etc/ldap/ssl/ldap-server-pubkey.pem -
    then
	echo "success: Client certificate for LDAP server matches slapd cert."
    else
	echo "error: Certificate in /etc/ldap/ssl/slapd.pem and /etc/ldap/ssl/ldap-server-pubkey.pem differ."
	RESULT=1
    fi
else
    echo "warning: Missing /etc/ldap/ssl/ldap-server-pubkey.pem"
fi

# Check if LDAP server can handle more than 1024 concurrent LDAP
# connections (ulimit for openfiles).  First flod LDAP server with
# connections, then try a simple search.  This used to fail with
# Debian Edu/Lenny, as slapd would stop working when it ran out of
# file descriptors.
ldap_server=ldap
limit=1200
perl -MNet::LDAP -e "sleep(5); my @c; for my \$n (0 .. $limit) { \$c[\$n] = Net::LDAP->new('ldap://$ldap_server', onerror => undef); my \$root = \$c[\$n]->root_dse() if \$c[\$n]; } sleep(5);"

if ldapsearch -s base -h $ldap_server -b '' -x '*' '+' > /dev/null 2>&1 ; then
    echo "success: $0: search work after flodding the LDAP server with $limit connections."
else 
    echo "error: $0: search fail after flodding the LDAP server with $limit connections"
    RESULT=1
fi

exit $RESULT
