#!/bin/sh -e

[ -n "$EX4DEBUG" ] && set -x

DIR=/etc/exim4
CACERT=$DIR/exim-ca.crt
CAKEY=$DIR/exim-ca.key
CADER=$DIR/exim-ca.der
CERT=$DIR/exim.crt
KEY=$DIR/exim.key

# This exim binary was built with GnuTLS which does not support dhparams
# from a file. See /usr/share/doc/exim4-base/README.TLS*
#DH=$DIR/exim.dhparam

if ! which openssl > /dev/null ;then
	echo "$0: openssl is not installed, exiting" 1>&2
	exit 1
fi

DAYS=3650

if [ "$1" != "--force" -a -f $CERT -a -f $KEY ]; then
  echo "[*] $CERT and $KEY exists!"
  echo "    Use \"$0 --force\" to force generation!"
  exit 0
fi

if [ "$1" = "--force" ]; then
  shift
fi     

#SSLEAY=/tmp/exim.ssleay.$$.cnf
SSLEAY=`tempfile -m600 -pexi`

cat > $SSLEAY <<EOM
RANDFILE = ~/.rnd
[ req ]
default_bits = 1024
default_keyfile = exim-ca.key
distinguished_name = req_distinguished_name
prompt = no
x509_extensions = v3_ca

[ v3_ca ]
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid:always,issuer:always
basicConstraints = CA:true
nsCertType = sslCA, emailCA

[ req_distinguished_name ]
countryName = DE
stateOrProvinceName = Baden-Wuerttemberg
localityName = Leinfelden-Echterdingen
organizationName = Mallorn CA
commonName = sirion.mallorn.de CA
emailAddress = ms@mallorn.de
EOM

echo "[*] Creating CA!"

openssl genrsa -out $CAKEY 1024
openssl req -config $SSLEAY -new -x509 -days 7305 -key $CAKEY -out $CACERT

chmod 0400 $CAKEY $CACERT

cat > $SSLEAY <<EOM
RANDFILE = ~/.rnd
[ req ]
default_bits = 1024
default_keyfile = exim.key
distinguished_name = req_distinguished_name
prompt = no
x509_extensions = usr_cert

[ usr_cert ]
basicConstraints=CA:FALSE
nsCertType = server

[ req_distinguished_name ]
countryName = DE
stateOrProvinceName = Baden-Wuerttemberg
localityName = Leinfelden-Echterdingen
organizationName = Mallorn
commonName = sirion.mallorn.de
emailAddress = ms@mallorn.de
EOM

echo "[*] Creating a self signed SSL certificate for Exim!"

REQ=`tempfile -m600 -pexi`

openssl genrsa -out $KEY 1024
openssl req -config $SSLEAY -new -key $KEY -out $REQ
openssl x509 -req -days $DAYS -in $REQ -CA $CACERT -CAkey $CAKEY -clrext -extfile $SSLEAY -extensions usr_cert -purpose -set_serial `date +%s` -out $CERT

openssl x509 -in $CACERT -outform DER -out $CADER

#openssl req -config $SSLEAY -x509 -newkey rsa:1024 -keyout $KEY -out $CERT -days $DAYS -nodes
#see README.TLS*# openssl dhparam -check -text -5 512 -out $DH
rm -f $SSLEAY $REQ

chown root:Debian-exim $KEY $CERT $DH
chmod 640 $KEY $CERT $DH

echo "[*] Done generating self signed certificates for exim!"


