#!/bin/bash

# nohup /kaz/bin/dynDNS.sh &

KAZ_ROOT=$(cd "$(dirname $0)"/..; pwd)
. "${KAZ_ROOT}/bin/.commonFunctions.sh"
setKazVars
. "${DOCKERS_ENV}"
# no more export in .env
export $(set | grep "domain=")

cd "${KAZ_ROOT}"
export PRG="$0"

export MYHOST="${site}"

MYIP_URL="https://kaz.bzh/myip.php"
DNS_IP=""

DELAI_WAIT=10 # DNS occupé
DELAI_GET=5 # min entre 2 requêtes
DELAI_CHANGE=3600 # propagation 1h
DELAI_NO_CHANGE=300 # pas de changement 5 min

BOLD='\e[1m'
RED='\e[0;31m'
GREEN='\e[0;32m'
YELLOW='\e[0;33m'
BLUE='\e[0;34m'
MAGENTA='\e[0;35m'
CYAN='\e[0;36m'
NC='\e[0m' # No Color
NL='
'

export VERBOSE=""
export SIMU=""

usage(){
    echo "Usage: ${PRG} list [sub-domain...]"
    echo "  -h help"
    echo "  -v verbose"
    echo "  -n simulation"
    exit 1
}

#. "${KAZ_KEY_DIR}/env-gandi"
. "${KAZ_KEY_DIR}/env-alwaysdata"
 
if [[ -z "${ALWAYSDATA_TOKEN}" ]] ; then
    echo "no ALWAYSDATA_TOKEN set in ${KAZ_KEY_DIR}/env-alwaysdata"
    usage
fi

DOMAIN_ID=$(curl -s -X GET --basic --user "${ALWAYSDATA_TOKEN} account=${ALWAYSDATA_ACCOUNT}:" ${ALWAYSDATA_API}/domain/?name=${domain} | jq '.[0].id')

if [[ -z "${DOMAIN_ID}" ]] ; then
    echo "no DOMAIN_ID give by alwaysdata"
    usage
fi

# if [[ -z "${GANDI_KEY}" ]] ; then
#     echo
#     echo "no GANDI_KEY set in ${KAZ_KEY_DIR}/env-gandi"
#     usage
#     exit
# fi

for ARG in $@
do
    case "${ARG}" in
	'-h' | '-help' )
	    usage
	    ;;
	'-v' )
	    shift
	    export VERBOSE=":"
	    ;;
	'-n' )
	    shift
	    export SIMU="echo"
	    ;;
	* )
	    usage
	    ;;
    esac
done

log () {
    echo -e "${BLUE}$(date +%d-%m-%Y-%H-%M-%S)${NC} : $*"
}

simu () {
    echo -e "${YELLOW}$(date +%d-%m-%Y-%H-%M-%S)${NC} : $*"
}

cmdWait () {
    #ex gandi
    #curl -H "authorization: Apikey ${GANDI_KEY}" --connect-timeout 2 -s -D - -o /dev/null "${GANDI_API}" 2>/dev/null
    curl -s -X GET --basic --user "${ALWAYSDATA_TOKEN} account=${ALWAYSDATA_ACCOUNT}:" --connect-timeout 2 -D - -o /dev/null "${ALWAYSDATA_API}/record/?domain=${DOMAIN_ID}&type=CNAME&name=${TARGET}" 2>/dev/null
}

waitNet () {
    ###  wait when error code 503
    if [[ $(cmdWait | head -n1) != *200* ]]; then
	log "DNS not available. Please wait..."
	while [[ $(cmdWait | head -n1) != *200* ]]; do
	    [[ -z "${VERBOSE}" ]] || simu curl -s -X GET --basic --user "${ALWAYSDATA_TOKEN} account=${ALWAYSDATA_ACCOUNT}:" --connect-timeout 2 -D - -o /dev/null "${ALWAYSDATA_API}/record/?domain=${DOMAIN_ID}&type=CNAME&name=${TARGET}"
	    sleep "${DELAI_WAIT}"
	done
	exit
    fi
}


getDNS () {
    # curl -s -X GET "${GANDI_API}/records" -H "authorization: Apikey ${GANDI_KEY}"|
    #     sed "s/,{/\n/g"|
    #     sed 's/.*rrset_name":"\([^"]*\)".*rrset_values":\["\([^"]*\)".*/\1:\2/g'|
    #     grep -e "^${MYHOST}:"|
    #     sed "s/^${MYHOST}://g" |
    # 	tr -d '\n\t\r '
    ${SIMU} curl -s -X GET --basic --user "${ALWAYSDATA_TOKEN} account=${ALWAYSDATA_ACCOUNT}:" "${ALWAYSDATA_API}/record/?domain=${DOMAIN_ID}&type=A&name=${MYHOST}" | jq '.[] | "\(.value)"' | tr -d '"'
}

saveDns () {
  mkdir -p /root/dns
  ${SIMU} curl -s -X GET --basic --user "${ALWAYSDATA_TOKEN} account=${ALWAYSDATA_ACCOUNT}:" "${ALWAYSDATA_API}/record/?domain=${DOMAIN_ID}" -o /root/dns/dns_save_$(date +'%Y%m%d%H%M%S')
}

setDNS () {
    saveDns
    # curl -s -X POST "${GANDI_API}/records" -H "authorization: Apikey  ${GANDI_KEY}" -H 'content-type: application/json' -d '{"rrset_type":"A", "rrset_name":"'${MYHOST}'", "rrset_values":["'${IP}'"]}'
    ${SIMU} curl -s -X POST -d "{\"domain\":\"${DOMAIN_ID}\", \"type\":\"A\", \"name\":\"${MYHOST}\", \"value\":\"${IP}\"}" --basic --user "${ALWAYSDATA_TOKEN} account=${ALWAYSDATA_ACCOUNT}:" "${ALWAYSDATA_API}/record/"

}

while :; do
    sleep "${DELAI_GET}"
    IP=$(curl -s "${MYIP_URL}" | grep -Eo '([0-9]{1,3}\.){3}[0-9]{1,3}' | tr -d '\n\t\r ')
    if ! [[ ${IP} =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
	log "BAB IP ${IP}" ; continue
    fi

    if [ -z "${DNS_IP}" ]; then
	# Variable pas encore initialisée
	waitNet
	DNS_IP=$(getDNS)

	if [ -z "${DNS_IP}" ]; then
	    # C'est la première fois que le site est en prod
	    log "set ${MYHOST} : ${IP}"
	    setDNS
	    DNS_IP=$(getDNS)
	    log "DNS set ${MYHOST}:${IP} (=${DNS_IP})"
	    sleep "${DELAI_CHANGE}"
	    continue
	fi
    fi

    if [ "${DNS_IP}" != "${IP}" ]; then
	log "${MYHOST} : ${DNS_IP} must change to ${IP}"
	# Changement d'adresse
	waitNet
	#curl -s -X DELETE "${GANDI_API}/records/${MYHOST}" -H "authorization: Apikey ${GANDI_KEY}"
	RECORD_ID=$(curl -s -X GET --basic --user "${ALWAYSDATA_TOKEN} account=${ALWAYSDATA_ACCOUNT}:" "${ALWAYSDATA_API}/record/?name=${MYHOST}&type=A&domain=${DOMAIN_ID}" | jq ".[] | select(.name==\"${MYHOST}\").id")
	${SIMU} curl -s -X DELETE --basic --user "${ALWAYSDATA_TOKEN} account=${ALWAYSDATA_ACCOUNT}:" "${ALWAYSDATA_API}/record/${RECORD_ID}/"
	setDNS
	DNS_IP=$(getDNS)
	log "DNS reset ${MYHOST}:${IP} (=${DNS_IP})"
	sleep "${DELAI_CHANGE}"
    else
	log "OK ${MYHOST}:${DNS_IP} / ${IP}"
	sleep ${DELAI_NO_CHANGE}
    fi
done
