#!/bin/bash

INTERVAL=60

dnsrecord="$DNS_RECORD"
zone="$DNS_ZONE"

cloudflare_token="$CLOUDFLARE_API_TOKEN"

# get the zone id for the requested zone
zoneid=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones?name=$zone&status=active" \
  -H "Authorization: Bearer $cloudflare_token" \
  -H "Content-Type: application/json" | jq -r '{"result"}[] | .[0] | .id')

if [ "$zoneid" == "null" ]; then
  echo "Zone not found, is your CloudFlare API key correct?"
  exit 1
fi

while true
do

wan_ip4=`dig @resolver4.opendns.com A myip.opendns.com +short -4`
wan_ip6=`dig @resolver1.ipv6-sandbox.opendns.com AAAA myip.opendns.com +short -6`

# update IPV4 record
published_ip4=`dig $dnsrecord A +short`
published_ip6=`dig $dnsrecord AAAA +short`

if [ "$published_ip4" != "$wan_ip4" ]; then
  echo "Updating $dnsrecord (zone $zoneid) A record from [$published_ip4] to [$wan_ip4]..."
  dnsrecordid=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones/$zoneid/dns_records?type=A&name=$dnsrecord" \
    -H "Authorization: Bearer $cloudflare_token" \
    -H "Content-Type: application/json" | jq -r '{"result"}[] | .[0] | .id')
  if [ "$dnsrecordid" == "null" ]; then
    curl -s -X POST "https://api.cloudflare.com/client/v4/zones/$zoneid/dns_records" \
      -H "Authorization: Bearer $cloudflare_token" \
      -H "Content-Type: application/json" \
      --data "{\"type\":\"A\",\"name\":\"$dnsrecord\",\"content\":\"$wan_ip4\",\"ttl\":1,\"proxied\":false}" | jq
  else
    curl -s -X PUT "https://api.cloudflare.com/client/v4/zones/$zoneid/dns_records/$dnsrecordid" \
      -H "Authorization: Bearer $cloudflare_token" \
      -H "Content-Type: application/json" \
      --data "{\"type\":\"A\",\"name\":\"$dnsrecord\",\"content\":\"$wan_ip4\",\"ttl\":1,\"proxied\":false}" | jq
  fi
fi

if [ "$published_ip6" != "$wan_ip6" ]; then
  echo "Updating $dnsrecord (zone $zoneid) AAAA record from [$published_ip6] to [$wan_ip6]..."
  dnsrecordid=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones/$zoneid/dns_records?type=AAAA&name=$dnsrecord" \
    -H "Authorization: Bearer $cloudflare_token" \
    -H "Content-Type: application/json" | jq -r '{"result"}[] | .[0] | .id')
  if [ "$dnsrecordid" == "null" ]; then
    curl -s -X POST "https://api.cloudflare.com/client/v4/zones/$zoneid/dns_records" \
      -H "Authorization: Bearer $cloudflare_token" \
      -H "Content-Type: application/json" \
      --data "{\"type\":\"AAAA\",\"name\":\"$dnsrecord\",\"content\":\"$wan_ip6\",\"ttl\":1,\"proxied\":false}" | jq
  else
    curl -s -X PUT "https://api.cloudflare.com/client/v4/zones/$zoneid/dns_records/$dnsrecordid" \
      -H "Authorization: Bearer $cloudflare_token" \
      -H "Content-Type: application/json" \
      --data "{\"type\":\"AAAA\",\"name\":\"$dnsrecord\",\"content\":\"$wan_ip6\",\"ttl\":1,\"proxied\":false}" | jq
  fi
fi

sleep $INTERVAL
done