#! @SHELL@
#
#
# 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=@mydatadir@/esmtpd.pem
fi

if test "@ssllib@" = "openssl"
then
	test -x @OPENSSL@ || exit 0
else
	test -x @CERTTOOL@ || exit 0
fi

if test -f "$PEMFILE"
then
	echo "$PEMFILE already exists."
	exit 1
fi

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

cd @mydatadir@
umask 077
BITS="$BITS"
set -e

if test "@ssllib@" = "openssl"
then
	cp /dev/null "$PEMFILE"
	chmod 600 "$PEMFILE"
	chown @mailuser@ "$PEMFILE"
	dd if=@RANDOMV@ of="$PEMFILE".rand count=1 2>/dev/null
	@OPENSSL@ req -new -x509 -days 365 -nodes \
		  -config @sysconfdir@/esmtpd.cnf -out "$PEMFILE" -keyout "$PEMFILE" || cleanup
	@OPENSSL@ dhparam -2 -rand "$PEMFILE".rand 512 >>"$PEMFILE" || cleanup
	@OPENSSL@ x509 -subject -dates -fingerprint -noout -in "$PEMFILE" || cleanup
	rm -f @mydatadir@/esmtpd.rand
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

	@CERTTOOL@ --generate-privkey --sec-param=$BITS --outfile "$PEMFILE".key || cleanup
	@CERTTOOL@ --generate-self-signed --load-privkey "$PEMFILE".key --outfile "$PEMFILE".cert --template @sysconfdir@/esmtpd.cnf || cleanup

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