#!/bin/bash
# how many days before the certificate expires should it be renewed
RENEW="28"
# how many days before the certificate expires should start sending alerts to the admin
ALERT="14"
ALERT_EMAIL='admin@your.domain'
# some variables set by ansible
SSL_BASEDIR="/etc/ssl"
ACME_LETSENCRYPT_BINARY="python /usr/local/bin/acme_tiny.py"
ACME_CHALLENGE_DIR="/var/www/acme-challenges"
ACME_LETSENCRYPT_DIR="${SSL_BASEDIR}/letsencrypt"
ACME_ACCOUNT_KEY="${ACME_LETSENCRYPT_DIR}/account.key"
# download lets-encrypt-x1-cross-signed.pem if the local copy is more than 3 days old
if [[ ! -r "${ACME_LETSENCRYPT_DIR}/lets-encrypt-x1-cross-signed.pem" || $(($(date +%s) - $(date -r "${ACME_LETSENCRYPT_DIR}/lets-encrypt-x1-cross-signed.pem" +%s))) -ge 259299 ]] ; then
curl --silent https://letsencrypt.org/certs/lets-encrypt-x1-cross-signed.pem > "${ACME_LETSENCRYPT_DIR}/lets-encrypt-x1-cross-signed.pem"
fi
for fqdn in www.domain1.foo www.domain2.foo ; do
# check if we have to renew a certificate
openssl x509 -noout -in "${ACME_LETSENCRYPT_DIR}/${fqdn}.crt" -checkend $( bc <<< "86400 * ${RENEW}") 2>/dev/null
if [[ $? -gt 0 ]] ; then
${ACME_LETSENCRYPT_BINARY} \
--account-key "${ACME_ACCOUNT_KEY}" \
--csr "${ACME_LETSENCRYPT_DIR}/${fqdn}.csr" \
--acme-dir "${ACME_CHALLENGE_DIR}" \
> "${ACME_LETSENCRYPT_DIR}/${fqdn}.crt"
cat "${ACME_LETSENCRYPT_DIR}/${fqdn}.crt" "${ACME_LETSENCRYPT_DIR}/lets-encrypt-x1-cross-signed.pem" \
> "${ACME_LETSENCRYPT_DIR}/${fqdn}.pem"
openssl x509 -noout -text -certopt no_header,no_version,no_pubkey -in "${ACME_LETSENCRYPT_DIR}/${fqdn}.crt" | \
mailx -s "[SSL] OK: ${fqdn} certificate was renewed" ${ALERT_EMAIL}
fi
# check if we need to alert about certificates that weren't renewed yet
openssl x509 -noout -in "${ACME_LETSENCRYPT_DIR}/${fqdn}.crt" -checkend $( bc <<< "86400 * ${ALERT}") 2>/dev/null
if [[ $? -gt 0 ]] ; then
openssl x509 -noout -text -certopt no_header,no_version,no_pubkey -in "${ACME_LETSENCRYPT_DIR}/${fqdn}.crt" | \
mailx -s "[SSL] ERROR: ${fqdn} certificate will expire soon and wasn't automatically renewed" ${ALERT_EMAIL}
fi
done