#! /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
# POP3 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/pop3d.pem
then
	echo "/usr/pkg/share/courier/pop3d.pem already exists."
	exit 1
fi

umask 077
set -e

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

cd /usr/pkg/share/courier
umask 077
BITS="$BITS"
set -e

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

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

	cp /dev/null /usr/pkg/share/courier/pop3d.key
	chmod 600 /usr/pkg/share/courier/pop3d.key
	cp /dev/null /usr/pkg/share/courier/pop3d.cert
	chmod 600 /usr/pkg/share/courier/pop3d.cert
	cp /dev/null /usr/pkg/share/courier/pop3d.pem
	chmod 600 /usr/pkg/share/courier/pop3d.pem
	chown root /usr/pkg/share/courier/pop3d.pem

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