#!/bin/bash

set -e

if [[ ! -f /etc/bondingadmin/.letsencrypt.enabled ]] ; then
    echo "Let's encrypt not enabled"
    exit 1
fi

# Parse DNS name from the settings
eval "$(ba print_settings DNS_NAME | sed 's/ //g')"

certbot revoke \
    -d "${DNS_NAME}" \
    --cert-path "/etc/letsencrypt/live/${DNS_NAME}/cert.pem"

# Remove the Let's encrypt links
rm -f /etc/bondingadmin/crt.pem
rm -f /etc/bondingadmin/key.pem

# Remove the previously issued certificates and configurations
rm -rf "/etc/letsencrypt/live/${DNS_NAME}"
rm -rf "/etc/letsencrypt/renewal/${DNS_NAME}.conf"
rm -rf "/etc/letsencrypt/archive/${DNS_NAME}"
rm -rf "/etc/letsencrypt/renewal-hooks/deploy/${DNS_NAME}"

# Warn about leftover files if the server's DNS name changed
LETSENCRYPT_DIRS="/etc/letsencrypt/live/ /etc/letsencrypt/renewal/ /etc/letsencrypt/archive/ /etc/letsencrypt/renewal-hooks/deploy/"
for dir in $LETSENCRYPT_DIRS ; do
    if [ -d $dir ] && [ ! -z "$(ls -A $dir)" ] ; then
        echo "$dir is not empty. Manually check and remove files before re-enabling Let's Encrypt."
    fi
done

# Restore the previous certs, if they exist
test -f /etc/bondingadmin/previous_certs/crt.pem && cp /etc/bondingadmin/previous_certs/crt.pem /etc/bondingadmin/crt.pem
test -f /etc/bondingadmin/previous_certs/key.pem && cp /etc/bondingadmin/previous_certs/key.pem /etc/bondingadmin/key.pem

rm -f /etc/bondingadmin/.letsencrypt.enabled

# Make nginx aware of the old certs
systemctl reload nginx
