#!/bin/bash
#
# Switch on TLS for exim.
# Create a self-signed certificate for exim4 and dovecot.
#

set -e

TEMPLATE="${target}/usr/share/ssl-cert/ssleay.cnf"
HostName="${HOSTNAME}.intern"

## Activate TLS for exim:
FILE=/etc/exim4/conf.d/main/000_localmacros
ainsl -a $FILE "MAIN_TLS_ENABLE = yes"

## Create exim certificate:
CERT="/etc/exim4/exim.crt"
KEY="/etc/exim4/exim.key"
CONF="/etc/exim4/exim.cnf"

if [ ! -f $target/$CERT ] || [ ! -f $target/$KEY ]; then
    sed -e s#@HostName@#"$HostName"# $TEMPLATE > ${target}/$CONF
    echo "subjectAltName=DNS:$HostName,DNS:mail.intern" >> ${target}/$CONF
    $ROOTCMD openssl req -config $CONF -new -x509 -days 7000 -nodes -out $CERT -keyout $KEY
    $ROOTCMD chmod 640 $KEY $CERT $CONF
    $ROOTCMD chown root:Debian-exim $KEY $CERT
else
    echo "$CERT and $KEY exists, nothing done!"
fi


## Create dovecot certificate:
CERT="/etc/dovecot/dovecot.pem"
KEY="/etc/dovecot/private/dovecot.pem"
CONF="/etc/dovecot/dovecot.cnf"

if [ ! -f ${target}/$CONF ] ; then
    sed -e s#@HostName@#"$HostName"# $TEMPLATE > ${target}/$CONF
    echo "subjectAltName=DNS:$HostName,DNS:mail.intern" >> ${target}/$CONF
    $ROOTCMD openssl req -config $CONF -new -x509 -days 7000 -nodes -out $CERT -keyout $KEY
    $ROOTCMD chmod 640 $KEY $CERT $CONF
    $ROOTCMD chown root:dovecot $KEY $CERT
    ## Switch on SSL:
    $ROOTCMD sed -i -e "s/^ssl = no/ssl = yes/" \
             -e "s/^#ssl_cert =/ssl_cert =/" \
             -e "s/^#ssl_key =/ssl_key =/" /etc/dovecot/conf.d/10-ssl.conf
else
    echo "${target}/$CONF exists, nothing done!"
fi
