#!/usr/bin/env bash

echo -e "\t\t\033[1;33m* initalizing certificates\033[0m"

if [ ! -d /data/ssl ]; then
    echo -e "\t\t\033[1;33m* creating /data/ssl directory for certificates\033[0m"
    cp -r /defaults/data/ssl /data/
fi
chown mail:mail /data/ssl -R

# uploaded from web-admin
if [ -f /tmp/server.crt ] && [ -f /tmp/server.key ] && [ -f /tmp/ca.crt ]; then
    echo "* processing certificate uploaded from web admin\033[0m"
    mv /tmp/server.crt /data/ssl/server.crt
    mv /tmp/server.key /data/ssl/server.key
    mv /tmp/ca.crt /data/ssl/ca.crt
    rm /etc/ssl/dh4096.pem
fi

if [ -f /data/ssl/server.crt ] && [ -f /data/ssl/server.key ] && [ -f /data/ssl/ca.crt ]; then
    echo -e "\t\t\033[1;33m* processing certificate from /data/ssl\033[0m"

    cp /data/ssl/ca.crt /etc/ssl/ca.crt
    cp /data/ssl/server.crt /etc/ssl/server.crt
    cp /data/ssl/server.key /etc/ssl/server.key

    if [ -f /data/ssl/dh4096.pem ]; then
        cp /data/ssl/dh4096.pem /etc/ssl/dh4096.pem
    fi

    mkdir /opt/haraka-smtp/config/ssl 2> /dev/null
fi

if [ -f /data/ssl/server.crt ]; then
    cp /data/ssl/server.crt /etc/ssl/server-combined.crt

    if [ -f /data/ssl/ca.crt ]; then
        echo "" >> /etc/ssl/server-combined.crt
        cat /data/ssl/ca.crt >> /etc/ssl/server-combined.crt
    fi
fi

if [ ! -f /etc/ssl/dh4096.pem ]; then
    echo -e "\t\t\033[1;33m* generating DH parameter\033[0m"
    (export RANDFILE=/tmp/.rnd && openssl dhparam -dsaparam -out /data/ssl/dh4096.pem 4096)
fi
if [ -f /data/ssl/dh4096.pem ]; then
    cp /data/ssl/dh4096.pem /etc/ssl/dh4096.pem
fi

ln -s /etc/ssl/server-combined.crt /opt/haraka-smtp/config/tls_cert.pem 2> /dev/null
ln -s /etc/ssl/server.key /opt/haraka-smtp/config/tls_key.pem 2> /dev/null
ln -s /etc/ssl/dh4096.pem /opt/haraka-smtp/config/dhparams.pem 2> /dev/null

ln -s /etc/ssl/server-combined.crt /opt/haraka-submission/config/tls_cert.pem 2> /dev/null
ln -s /etc/ssl/server.key /opt/haraka-submission/config/tls_key.pem 2> /dev/null
ln -s /etc/ssl/dh4096.pem /opt/haraka-submission/config/dhparams.pem 2> /dev/null

exit 0