#!/usr/bin/env bash
#

set -euf -o pipefail

# ************** USAGE **************
#
# Example usage (with this hook file saved in /root/):
#
#   sudo su -
#   certbot certonly --manual --preferred-challenges dns --manual-public-ip-logging-ok --agree-tos -d "5apps.com" -d muc.5apps.com -d "xmpp.5apps.com" \
#     --manual-auth-hook "/root/letsencrypt_hook.sh auth" --manual-cleanup-hook "/root/letsencrypt_hook.sh cleanup"
#
# This hook requires configuration, continue reading.
#
# ************** CONFIGURATION **************
#
# GANDI_API_KEY: Your Gandi Live API key
#
# PROVIDER_UPDATE_DELAY:
#   How many seconds to wait after updating your DNS records. This may be required,
#   depending on how slow your DNS host is to begin serving new DNS records after updating
#   them via the API. 30 seconds is a safe default, but some providers can be very slow
#   (e.g. Linode).
#
#   Defaults to 30 seconds.
#
GANDI_API_KEY="<%= @gandi_api_key %>"
PROVIDER_UPDATE_DELAY=30

regex='.*\.(.*\..*)'
if [[ $CERTBOT_DOMAIN =~ $regex ]]
then
  DOMAIN="${BASH_REMATCH[1]}"
else
  DOMAIN="${CERTBOT_DOMAIN}"
fi

# To be invoked via Certbot's --manual-auth-hook
function auth {
    curl -s -D- -H "Content-Type: application/json" \
        -H "X-Api-Key: ${GANDI_API_KEY}" \
        -d "{\"rrset_name\": \"_acme-challenge.${CERTBOT_DOMAIN}.\",
             \"rrset_type\": \"TXT\",
             \"rrset_ttl\": 3600,
             \"rrset_values\": [\"${CERTBOT_VALIDATION}\"]}" \
        "https://dns.api.gandi.net/api/v5/domains/${DOMAIN}/records"


    sleep ${PROVIDER_UPDATE_DELAY}
}

# To be invoked via Certbot's --manual-cleanup-hook
function cleanup {
    curl -s -X DELETE -H "Content-Type: application/json" \
        -H "X-Api-Key: ${GANDI_API_KEY}" \
        https://dns.api.gandi.net/api/v5/domains/${DOMAIN}/records/_acme-challenge.${CERTBOT_DOMAIN}./TXT
}

HANDLER=$1; shift;
if [ -n "$(type -t $HANDLER)" ] && [ "$(type -t $HANDLER)" = function ]; then
  $HANDLER "$@"
fi
