#!/bin/bash
#
# Create a self-signed certificate for dovecot.
# Based upon a script from debian-lan-config by Andreas B. Mundt.
#

set -e

TEMPLATE="/usr/share/ssl-cert/ssleay.cnf"
HostName="postoffice.intern"

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

if [ ! -f $CONF ] ; then
    sed -e s#@HostName@#"$HostName"# $TEMPLATE > $CONF
    echo "subjectAltName=DNS:$HostName,DNS:postoffice.intern" >> $CONF
    openssl req -config $CONF -new -x509 -days 7000 -nodes -out $CERT -keyout $KEY
    chmod 640 $KEY $CERT $CONF
    chown root:dovecot $KEY $CERT
    ## Switch on SSL:
    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 "$CONF exists, nothing done!"
fi
