#! @SHELL@
#
# $Id: mkimapdcert.in,v 1.7 2007/11/04 20:49:58 mrsam Exp $
#
# 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.

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

prefix="@prefix@"

if test -f @mydatadir@/imapd.pem
then
	echo "@mydatadir@/imapd.pem already exists."
	exit 1
fi

umask 077

cleanup() {
	rm -f @mydatadir@/imapd.pem
	rm -f @mydatadir@/imapd.rand
	rm -f @mydatadir@/imapd.key
	rm -f @mydatadir@/imapd.cert
	exit 1
}

cd @mydatadir@

if test "@ssllib@" = "openssl"
then
	cp /dev/null @mydatadir@/imapd.pem
	chmod 600 @mydatadir@/imapd.pem
	chown @mailuser@ @mydatadir@/imapd.pem

	dd if=@RANDOMV@ of=@mydatadir@/imapd.rand count=1 2>/dev/null
	@OPENSSL@ req -new -x509 -days 365 -nodes \
		  -config @sysconfdir@/imapd.cnf -out @mydatadir@/imapd.pem -keyout @mydatadir@/imapd.pem || cleanup
	@OPENSSL@ gendh -rand @mydatadir@/imapd.rand 512 >>@mydatadir@/imapd.pem || cleanup
	@OPENSSL@ x509 -subject -dates -fingerprint -noout -in @mydatadir@/imapd.pem || cleanup
	rm -f @mydatadir@/imapd.rand
else
	cp /dev/null @mydatadir@/imapd.key
	chmod 600 @mydatadir@/imapd.key
	cp /dev/null @mydatadir@/imapd.cert
	chmod 600 @mydatadir@/imapd.cert

	@CERTTOOL@ --generate-privkey --outfile imapd.key
	@CERTTOOL@ --generate-self-signed --load-privkey imapd.key --outfile imapd.cert --template @sysconfdir@/imapd.cnf
	@CERTTOOL@ --generate-dh-params >>imapd.cert
	cat imapd.key imapd.cert >imapd.pem
	rm -f imapd.key imapd.cert
fi
