#!/bin/bash

. /etc/ddns/ddns.conf

IFS=, HOSTS=($HOSTNAME)
MAINHOST=$HOSTS

if [ -z "$SLEEP" ] ; then
  $SLEEP=60
fi

while :

do

echo "Sleeping..."
sleep $SLEEP

new_ip_address=$(curl -4 $URL | sed 's/[ \t\n]*$//')

result=$(whois $new_ip_address)

if [ $? = 0 ]
then

# Ignoring, if after mobile NAT
cnt=`echo "$result" | grep descr | grep -i 'beeline\|mts\|megafon' | wc -l`

if [ $cnt -gt 0 ]
then
  echo "Mobile NAT detected, backup channel, no action taken"
  continue
fi

if [ -z "$new_ip_address" ] ; then
  echo "New IP unknown"
  continue
fi  

if [ -z "$old_ip_address" ] ; then
  old_ip_address=$(host -W 1 -R 4 -4 -t A $MAINHOST $SERVER | grep "has address" | awk '{print $4}')
  old_ip_address=$(echo $old_ip_address)
  if [ -z "$old_ip_address" ] ; then
    echo "Old IP unknown"
    continue
  fi
fi  

echo "[$old_ip_address],[$new_ip_address]"

if [ "$old_ip_address" = "$new_ip_address" ] ; then

  echo "IP not changed, no action"

else

  for host in ${HOSTS[@]}; do
    nsupdate -v -k $KEYFILE << EOF
server $SERVER
zone $ZONE
update delete $host A
update add $host $TTL A $new_ip_address
send
EOF

    echo "DNS update for $host"
  done  
  
  unset old_ip_address

  if [ ! -z "$EXEC" ]
  then
    $EXEC
  fi

fi

fi

done