#!/bin/sh -e
#
# Test if the LDAP server is working.
# $Id: ldap-server 67570 2010-07-31 06:15:26Z 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

exit $RESULT
