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

PEMFILE="$1"

if [ -z "$PEMFILE" ]; then
	PEMFILE=/usr/pkg/share/courier/esmtpd
fi

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 "$PEMFILE".pem
then
	echo "${PEMFILE}.pem already exists."
	exit 1
fi

cleanup() {
	rm -f "$PEMFILE".rand
	rm -f "$PEMFILE".pem
	rm -f "$PEMFILE".key
	rm -f "$PEMFILE".cert
	exit 1
}

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

if test "$ssllib" = "openssl"
then
	cp /dev/null "$PEMFILE".pem
	chmod 600 "$PEMFILE".pem
	chown courier "$PEMFILE".pem
	dd if=/dev/urandom of="$PEMFILE".rand count=1 2>/dev/null
	/usr/bin/openssl req -new -x509 -days 365 -nodes \
		  -config /usr/pkg/etc/courier/esmtpd.cnf -out "$PEMFILE".pem -keyout "$PEMFILE".pem || cleanup

	if test "$BITS" = ""
	then
		BITS="2048"
	fi

	/usr/bin/openssl dhparam -2 -rand "$PEMFILE".rand $BITS >>"$PEMFILE".pem || cleanup
	/usr/bin/openssl x509 -text -noout -in "$PEMFILE".pem > "$PEMFILE".cert || cleanup
	cat "$PEMFILE".cert >>"$PEMFILE".pem
	rm -f "$PEMFILE".rand "$PEMFILE".cert
else
	if test "$BITS" = ""
	then
		BITS="high"
	fi

	cp /dev/null "$PEMFILE".key
	chmod 600 "$PEMFILE".key
	cp /dev/null "$PEMFILE".cert
	chmod 600 "$PEMFILE".cert

	/usr/pkg/bin/certtool --generate-privkey --sec-param=$BITS --outfile "$PEMFILE".key || cleanup
	/usr/pkg/bin/certtool --generate-self-signed --load-privkey "$PEMFILE".key --outfile "$PEMFILE".cert --template /usr/pkg/etc/courier/esmtpd.cnf || cleanup

	cp /dev/null "$PEMFILE".pem
	chmod 600 "$PEMFILE".pem
	chown courier "$PEMFILE".pem
	cat "$PEMFILE".key "$PEMFILE".cert >"$PEMFILE".pem
	rm -f "$PEMFILE".key "$PEMFILE".cert
fi
