#!/bin/sh
set -euC

# nfsn-dns-certbot DOMAIN NAME EMAIL_NAME INSTALLER [CERTBOT_ARG]...

# nfsn-dns-certbot "example.com" "" "" ""
# nfsn-dns-certbot "example.com" "git" "" "apache" --quiet

# Arguments.

domain="$1" ; shift
name="$1" ; shift
email_name="${1:-"hostmaster"}" ; shift
installer="${1:-}" ; shift

# Certbot.

host="${name:+"$name."}$domain"
dir="$(cd "$(dirname "$0")" ; pwd)"

certbot certonly \
    --non-interactive \
    --email "$email_name@$host" \
    --agree-tos \
    --manual \
    --manual-public-ip-logging-ok \
    --manual-auth-hook "$dir/nfsn-dns-certbot-auth" \
    --manual-cleanup-hook "$dir/nfsn-dns-certbot-cleanup" \
    --preferred-challenges="dns" \
    --domains "$host" \
    "$@"

if [ -n "$installer" ]
then
    certbot install \
        --cert-name "$host" \
        --installer "$installer" \

    certbot enhance \
        --non-interactive \
        --cert-name "$host" \
        --domain "$host" \
        --installer "$installer" \
        --redirect \
        --hsts \
        --uir
fi