#!/bin/bash

set -e

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

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

apt-get install certbot --assume-yes

mkdir --parents /var/lib/bondingadmin/certbot/
certbot certonly \
    --webroot \
    --webroot-path=/var/lib/bondingadmin/certbot/ \
    -d "${DNS_NAME}" \
    --agree-tos \
    --email techservices@multapplied.net

cat <<EOF > /etc/letsencrypt/renewal-hooks/deploy/${DNS_NAME}
systemctl reload nginx
EOF

chmod +x /etc/letsencrypt/renewal-hooks/deploy/${DNS_NAME}

# Backup the current certificates, if they exist
mkdir --parents /etc/bondingadmin/previous_certs
test -f /etc/bondingadmin/crt.pem  && mv /etc/bondingadmin/crt.pem /etc/bondingadmin/previous_certs/
test -f /etc/bondingadmin/key.pem  && mv /etc/bondingadmin/key.pem /etc/bondingadmin/previous_certs/

# symlink in the letsencrypt certificates
ln -sn "/etc/letsencrypt/live/${DNS_NAME}/fullchain.pem" /etc/bondingadmin/crt.pem
ln -sn "/etc/letsencrypt/live/${DNS_NAME}/privkey.pem" /etc/bondingadmin/key.pem

# allow bondingadmin to read the certificate for the HTTPS Security page
chmod go+Xr /etc/letsencrypt/live/ /etc/letsencrypt/archive/

# Make nginx aware of the change
systemctl reload nginx

touch /etc/bondingadmin/.letsencrypt.enabled
