#!/bin/bash

certbot_cmd() {
    sudo docker-compose run --rm --entrypoint "$1" certbot
}

install_dir="{{ install_dir }}"
domain="{{ custom_domain }}"
email="{{ letsencrypt_email }}"
is_ssl_staging="{{ is_ssl_staging }}"


echo "Creating certificate for '$domain'."

rsa_key_size=4096
data_path="$install_dir/data/certbot"

sudo chown -R ubuntu:ubuntu "$data_path"

mkdir -p "$data_path"/{conf,www}

if ! [[ -e "$data_path/conf/options-ssl-nginx.conf" && -e "$data_path/conf/ssl-dhparams.pem" ]]; then
    echo "### Downloading recommended TLS parameters..."
    curl -s https://raw.githubusercontent.com/certbot/certbot/master/certbot-nginx/certbot_nginx/_internal/tls_configs/options-ssl-nginx.conf > "$data_path/conf/options-ssl-nginx.conf"
    curl -s https://raw.githubusercontent.com/certbot/certbot/master/certbot/certbot/ssl-dhparams.pem > "$data_path/conf/ssl-dhparams.pem"
    echo
fi

echo "### Requesting Let's Encrypt certificate for '$domain'..."

if [[ -z $email ]]; then
    email_arg="--register-unsafely-without-email"
else
    email_arg="--email $email --no-eff-email"
fi

if [[ $is_ssl_staging == "true" ]]; then
    staging_arg="--staging"
else
    staging_arg=""
fi


echo "### Generating OpenSSL key for '$domain'..."
live_path="/etc/letsencrypt/live/$domain"

cd "$install_dir"

certbot_cmd \
    "sh -c \"mkdir -p '$live_path' && openssl req -x509 -nodes -newkey rsa:1024 -days 1 \
        -keyout '$live_path/privkey.pem' \
        -out '$live_path/fullchain.pem' \
        -subj '/CN=localhost' \
        \""
echo

echo "### Starting nginx..."
sudo docker-compose up --force-recreate --detach nginx
echo

echo "### Removing key now that validation is done for $domain..."
certbot_cmd \
    "rm -Rfv /etc/letsencrypt/live/$domain /etc/letsencrypt/archive/$domain /etc/letsencrypt/renewal/$domain.conf"
echo

# The following command exits with a non-zero status code even if the certificate was generated, but some checks failed.
# So we explicitly ignore such failure with a `|| true` in the end, to avoid bash quitting on us because this looks like
# a failed command.
certbot_cmd "certbot certonly --webroot --webroot-path=/var/www/certbot \
        $staging_arg \
        $email_arg \
        --domains $domain \
        --rsa-key-size $rsa_key_size \
        --agree-tos \
        --force-renewal" \
    || true
echo

echo "### Reloading nginx..."
sudo docker-compose exec nginx nginx -s reload
