#!/bin/bash

# Usage (achtung! dry-run mod): certbot certonly --manual --manual-public-ip-logging-ok --preferred-challenges=dns -d *.example.com -d example.com --manual-auth-hook /root/lew_dnsmgr_hook.sh --manual-cleanup-hook /root/lew_dnsmgr_hook_del.sh --dry-run

DNSMGR="https://msk-dns2.hoztnode.net/manager/dnsmgr"
DNSUSER="_DNSUSER_"
DNSUSERPASS="_DNSUSERPASS_"

PATH_LOG="/tmp/certbot_wildcard.log"

echo "- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -"
date +"%d-%m-%Y %H:%M" | tee -a $PATH_LOG
echo "Domain: $CERTBOT_DOMAIN" | tee -a $PATH_LOG
echo "New TXT: $CERTBOT_VALIDATION" | tee -a $PATH_LOG

echo -ne "Create record - " | tee -a $PATH_LOG
# Create record
res=$(curl -ks "$DNSMGR?authinfo=$DNSUSER:$DNSUSERPASS&out=text&func=domain.record.edit&plid=$CERTBOT_DOMAIN&name=_acme-challenge&rtype=txt&value=$CERTBOT_VALIDATION&sok=ok")
if [[ `echo "$res" | grep OK` ]]; then
    echo "OK" | tee -a $PATH_LOG
else
    echo "FALSE ($(echo "$res"))" | tee -a $PATH_LOG
    exit
fi

echo -ne "Wait resolving TXT record... " | tee -a $PATH_LOG
NS=$(dig +short $CERTBOT_DOMAIN. ns | head -n 1)
while [[ ! `dig +short _acme-challenge.$CERTBOT_DOMAIN. txt @$NS | grep -w "$CERTBOT_VALIDATION"` ]]; do sleep 60; done
echo "OK" | tee -a $PATH_LOG
echo "- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -"

