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

if test "openssl" = "openssl"
then
	test -x /usr/sbin/openssl || exit 0
else
	test -x /usr/local/bin/certtool || exit 0
fi

prefix="/usr/local"

if test -f /etc/ssl/private/imapd.pem
then
	echo "/etc/ssl/private/imapd.pem already exists."
	exit 1
fi

umask 077

cleanup() {
	rm -f /etc/ssl/private/imapd.pem
	rm -f /etc/ssl/private/imapd.rand
	rm -f /etc/ssl/private/imapd.key
	rm -f /etc/ssl/private/imapd.cert
	exit 1
}

cd /etc/ssl/private

if test "openssl" = "openssl"
then
	cp /dev/null /etc/ssl/private/imapd.pem
	chmod 600 /etc/ssl/private/imapd.pem
	chown _courier /etc/ssl/private/imapd.pem

	dd if=/dev/arandom of=/etc/ssl/private/imapd.rand count=1 2>/dev/null
	/usr/sbin/openssl req -new -x509 -days 365 -nodes \
		  -config /etc/courier/imapd.cnf -out /etc/ssl/private/imapd.pem -keyout /etc/ssl/private/imapd.pem || cleanup
	/usr/sbin/openssl gendh -rand /etc/ssl/private/imapd.rand 512 >>/etc/ssl/private/imapd.pem || cleanup
	/usr/sbin/openssl x509 -subject -dates -fingerprint -noout -in /etc/ssl/private/imapd.pem || cleanup
	rm -f /etc/ssl/private/imapd.rand
else
	cp /dev/null /etc/ssl/private/imapd.key
	chmod 600 /etc/ssl/private/imapd.key
	cp /dev/null /etc/ssl/private/imapd.cert
	chmod 600 /etc/ssl/private/imapd.cert
	cp /dev/null /etc/ssl/private/imapd.pem
	chmod 600 /etc/ssl/private/imapd.pem

	/usr/local/bin/certtool --generate-privkey --outfile imapd.key
	/usr/local/bin/certtool --generate-self-signed --load-privkey imapd.key --outfile imapd.cert --template /etc/courier/imapd.cnf
	/usr/local/bin/certtool --generate-dh-params >>imapd.cert
	cat imapd.key imapd.cert >imapd.pem
	rm -f imapd.key imapd.cert
fi
