#!/bin/sh
#
# Author: Rune Nordbøe Skillingstad <rune@skillingtad.no>
# Date: 2003-02-12
#
# Create a TLS certificate for slapd. To change default settings,
# edit /etc/ldap/ssl/slapd-cert.cnf
#

#set -x

opensslbin=/usr/bin/openssl

umask 077

certconf=/etc/ldap/ssl/slapd-cert.cnf
privkey=/etc/ldap/ssl/slapd.pem
pubkey=/etc/ldap/ssl/ldap-server-pubkey.pem

if test -x $opensslbin ; then
    :
else
    echo "error: can't find openssl." 1>&2
    exit 1
fi

if [ ! -f $certconf ] ; then
    echo "warning: missing certificate configuration file $certconf." 1>&2
fi

## Somtimes the installer stops when creating the certificate (#630970).
if [ ! -f /var/lib/urandom/random-seed ] ; then
    echo "/var/lib/urandom/random-seed not found, invoking /etc/init.d/urandom." 1>&2
    mkdir -p /var/lib/urandom
    /etc/init.d/urandom start
fi

mkdir -p /etc/ldap/ssl
chmod 751 /etc/ldap/ssl

if [ -f $privkey ] ; then
    echo "warning: private key $privkey already exist.  Exiting." 1>&2
    exit 1;
fi

TMPFILE=`mktemp`

# lifetime 10 years
$opensslbin req -new -x509 -nodes -sha1 \
      -config $certconf -days 3650 \
      -out $privkey -keyout $privkey >> $TMPFILE 2>&1 \
  || echo "error: problems running openssl." 1>&2

sedextract='/-----BEGIN CERTIFICATE-----/,/-----END CERTIFICATE-----/p'
sed -n "$sedextract" < $privkey > $pubkey

rm $TMPFILE

# Make sure the private key is only readable by user openldap
chown openldap:openldap $privkey
chmod 600 $privkey

# And the public key is readable by everyone
chmod 644 $pubkey
