#!/bin/sh

#   -------------------------------------------------------------
#   Propagate a Let's encrypt certificate to the mail server
#   - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#   Project:        Nasqueron
#   Created:        2016-05-21
#   License:        Trivial work, not eligible to copyright
#   Dependencies:   OpenSSL
#   -------------------------------------------------------------

#   -------------------------------------------------------------
#   Configuration
#   -------------------------------------------------------------

# Relevant paths
LETSENCRYPT_CERT_FOLDER=/data/letsencrypt/etc/live/mail.nasqueron.org-0001
MAILSERVER_CERT_FOLDER=/var/lib/lxc/mailserver/rootfs/etc/ssl/certs
HASH_FOLDER=/tmp

# To identify an unique certifate, we use the following content and path
# for an hash file.
ACTUAL_HASH=`openssl sha256 $LETSENCRYPT_CERT_FOLDER/cert.pem`
HASH_FILE = $HASH_FOLDER/hash-cert-`openssl sha256 $LETSENCRYPT_CERT_FOLDER`

#   -------------------------------------------------------------
#   Helper methods
#   -------------------------------------------------------------

# Determines if we should propagate a new certificate
should_propagate() {
	if [ ! -f $HASH_FILE ]; then
		return 1
	elif is_cert_hash_changed; then
		return 1
	else
		return 0
	fi
}

# Determines if the certificate has been modified, based on last recorded hash
is_cert_hash_changed() {
	EXPECTED_HASH=`cat $HASH_FILE`

	if [ "$ACTUAL_HASH" = "$EXPECTED_HASH" ]; then
		return 0
	else
		return 1
	fi
}

# Saves the new certificate hash
save_certificate_hash() {
	echo $ACTUAL_HASH > $HASH_FILE
}

#   -------------------------------------------------------------
#   Procedural code
#   -------------------------------------------------------------

if should_propagate; then
	echo cp $LETSENCRYPT_CERT_FOLDER/fullchain.pem $MAILSERVER_CERT_FOLDER/mailserver.crt
	echo cp $LETSENCRYPT_CERT_FOLDER/privkey.pem $MAILSERVER_CERT_FOLDER/mailserver.key
	save_certificate_hash
fi