#!/usr/bin/env bash
if [[ ! $1 ]]; then
    echo "Usage: $0 {create|cleanup}"
    echo "Place the private key in /etc/transip/ as privatekey.pem and create a file username.txt in /etc/transip/ with your username"
    echo "certbot certonly --manual --preferred-challenges=dns --manual-auth-hook \"$0 create\" --manual-cleanup-hook \"$0 cleanup\" -d yourdomain.com -d *.yourdomain.com"
    exit 1
fi

if [[ ! -f /etc/transip/privatekey.pem || ! -f /etc/transip/username.txt ]]; then
    echo "Could not find privatekey.pem or username.txt in /etc/transip/"
    exit 1
fi

if [ -z "$CERTBOT_DOMAIN" ] || [ -z "$CERTBOT_VALIDATION" ]; then
    echo "This script is intended to be used as a Certbot DNS hook."
    echo "Please set the CERTBOT_DOMAIN and CERTBOT_VALIDATION environment variables."
    exit 1
fi

USERNAME=$(cat /etc/transip/username.txt)
REQUEST_BODY='{ "login": "'$USERNAME'", "nonce": "'$(uuidgen 2>/dev/null | sha256sum | cut -c1-32)'", "read_only": false, "expiration_time": "1 minute", "label": "AutoGenerated by '$HOSTNAME' ['$(date +%s)']", "global_key": true }'
RESPONSE=$(curl -s -X POST https://api.transip.nl/v6/auth \
  -H "Content-Type: application/json" \
  -H "Signature: $(printf "%s" "$REQUEST_BODY" | openssl dgst -sha512 -sign /etc/transip/privatekey.pem | base64 | tr -d '\n')" \
  -d "$REQUEST_BODY"
)
API_TOKEN=$(echo "$RESPONSE" | grep -o '"token":"[^"]*"' | cut -d':' -f2 | tr -d '"')
ERROR=$(echo "$RESPONSE" | grep -o '"error":"[^"]*"' | cut -d':' -f2 | tr -d '"')

if [[ ! "$API_TOKEN" ]]; then
  echo "Error: $ERROR"
  exit 1
fi

DOUBLEDOTTED=("uk" "au" "nz" "za" "in" "br" "ar" "jp" "kr" "pk" "lk" "tr" "il" "ka" "tz" "ug" "zw" "mx" "cn" "sg" "my" "hk" "tw" "th" "id" "ph" "bd")
EXTENTION=$(echo ${CERTBOT_DOMAIN} | rev | cut -d '.' -f 1,1 | rev)
if [[ " ${DOUBLEDOTTED[@]} " =~ " ${EXTENTION} " ]]; then
    ZONE=$(echo "${CERTBOT_DOMAIN}" | rev | cut -d '.' -f 1-3 | rev)
    SUBDOMAIN=$(echo "${CERTBOT_DOMAIN}" | sed "s/\.${ZONE}$//")
else
    ZONE=$(echo "${CERTBOT_DOMAIN}" | rev | cut -d '.' -f 1-2 | rev)
    SUBDOMAIN=$(echo "${CERTBOT_DOMAIN}" | sed "s/\.${ZONE}$//")
fi

RECORD="_acme-challenge"
if [ -z $SUBDOMAIN ]; then
    RECORD="_acme-challenge"
else
    WILDCARD=$(echo "${SUBDOMAIN}" | cut -d '.' -f 1)
    if [ "$WILDCARD" = "*" ]; then
        SUBDOMAIN=$(echo "${SUBDOMAIN}" | sed 's/^\*\.//')
    fi
    RECORD="_acme-challenge.${SUBDOMAIN}"
fi

if [[ "$1" = "create" ]]; then
    RESPONSE=$(curl -s --write-out '%{http_code}' --output /dev/null -X POST \
   	-H "Authorization: Bearer $API_TOKEN" \
   	-H "Content-Type: application/json" \
    -d '{ "dnsEntry": { "name": "'${RECORD}'","expire": 60,"type": "TXT","content": "'${CERTBOT_VALIDATION}'" } }' \
   	"https://api.transip.nl/v6/domains/${ZONE}/dns")
    if [[ "$RESPONSE" != 201 ]]; then
        echo "Failed to create DNS record. HTTP status code: $RESPONSE"
        exit 1
    fi
    sleep 30
    exit 0
elif [[ "$1" = "cleanup" ]]; then
    RESPONSE=$(curl -s --write-out '%{http_code}' --output /dev/null -X DELETE \
   	-H "Authorization: Bearer $API_TOKEN" \
   	-H "Content-Type: application/json" \
    -d '{ "dnsEntry": { "name": "'${RECORD}'","expire": 60,"type": "TXT","content": "'${CERTBOT_VALIDATION}'" } }' \
   	"https://api.transip.nl/v6/domains/${ZONE}/dns")
    if [[ "$RESPONSE" != 204 ]]; then
        echo "Failed to cleanup DNS record. HTTP status code: $RESPONSE"
        exit 1
    fi
    exit 0
fi
