#! /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.

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

prefix="/usr/pkg"

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

umask 077
set -e

BITS="$BITS"

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

cd /usr/pkg/share/courier

if test "$ssllib" = "openssl"
then
	cp /dev/null /usr/pkg/share/courier/imapd.pem
	chmod 600 /usr/pkg/share/courier/imapd.pem
	chown root /usr/pkg/share/courier/imapd.pem

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

	/usr/pkg/bin/certtool --generate-privkey --sec-param=$BITS --outfile imapd.key
	/usr/pkg/bin/certtool --generate-self-signed --load-privkey imapd.key --outfile imapd.cert --template /usr/pkg/etc/courier/imapd.cnf
	cat imapd.key imapd.cert >imapd.pem
	rm -f imapd.key imapd.cert
fi
