#! /bin/sh
#
#
# Copyright 2000-2007 Double Precision, Inc.  See COPYING for
# distribution information.
#
# This is a short script to q`uickly generate a self-signed X.509 key for
# ESMTP STARTTLS.  Normally this script would get called by an automatic
# package installation routine.

case "$1" in
gnutls)		ssllib=gnutls ;;
openssl)	ssllib=openssl ;;
*)		ssllib="openssl" ;;
esac

if test "$ssllib" = "openssl"
then
	test -x /usr/bin/openssl || exit 0
else
	test -x /usr/pkg/bin/certtool || exit 0
fi

if test -f /usr/pkg/etc/courier/esmtpd.pem
then
	echo "/usr/pkg/etc/courier/esmtpd.pem already exists."
	exit 1
fi

cleanup() {
	rm -f /usr/pkg/etc/courier/esmtpd.rand
	rm -f /usr/pkg/etc/courier/esmtpd.pem
	rm -f /usr/pkg/etc/courier/esmtpd.key
	rm -f /usr/pkg/etc/courier/esmtpd.cert
	exit 1
}

cd /usr/pkg/etc/courier

if test "$ssllib" = "openssl"
then
	cp /dev/null /usr/pkg/etc/courier/esmtpd.pem
	chmod 600 /usr/pkg/etc/courier/esmtpd.pem
	chown courier /usr/pkg/etc/courier/esmtpd.pem
	dd if=/dev/urandom of=/usr/pkg/etc/courier/esmtpd.rand count=1 2>/dev/null
	/usr/bin/openssl req -new -x509 -days 365 -nodes \
		  -config /usr/pkg/etc/courier/esmtpd.cnf -out /usr/pkg/etc/courier/esmtpd.pem -keyout /usr/pkg/etc/courier/esmtpd.pem || cleanup
	/usr/bin/openssl gendh -rand /usr/pkg/etc/courier/esmtpd.rand 512 >>/usr/pkg/etc/courier/esmtpd.pem || cleanup
	/usr/bin/openssl x509 -subject -dates -fingerprint -noout -in /usr/pkg/etc/courier/esmtpd.pem || cleanup
	rm -f /usr/pkg/etc/courier/esmtpd.rand
else
	cp /dev/null /usr/pkg/etc/courier/esmtpd.key
	chmod 600 /usr/pkg/etc/courier/esmtpd.key
	cp /dev/null /usr/pkg/etc/courier/esmtpd.cert
	chmod 600 /usr/pkg/etc/courier/esmtpd.cert

	/usr/pkg/bin/certtool --generate-privkey --outfile esmtpd.key
	/usr/pkg/bin/certtool --generate-self-signed --load-privkey esmtpd.key --outfile esmtpd.cert --template /usr/pkg/etc/courier/esmtpd.cnf
	/usr/pkg/bin/certtool --generate-dh-params >>esmtpd.cert

	cp /dev/null /usr/pkg/etc/courier/esmtpd.pem
	chmod 600 /usr/pkg/etc/courier/esmtpd.pem
	cat esmtpd.key esmtpd.cert >esmtpd.pem
	rm -f esmtpd.key esmtpd.cert
fi
