#! /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/local/etc/courier/esmtpd
fi

if test "openssl" = "openssl"
then
	test -x /usr/bin/openssl || exit 0
else
	test -x /usr/local/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/local/etc/courier
umask 077
BITS="$BITS"
set -e

if test "openssl" = "openssl"
then
	cp /dev/null "$PEMFILE".pem
	chmod 600 "$PEMFILE".pem
	/usr/sbin/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/local/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/local/bin/certtool --generate-privkey --sec-param=$BITS --outfile "$PEMFILE".key || cleanup
	/usr/local/bin/certtool --generate-self-signed --load-privkey "$PEMFILE".key --outfile "$PEMFILE".cert --template /usr/local/etc/courier/esmtpd.cnf || cleanup

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