#!/bin/sh

# dnsstock_update.sh
#
# dns stock DDNS update script
# forIPv4 only
# by geohei <georges@geohei.lu>
# created : 28.03.2016
# revised : 02.04.2016 - added 'dyndns.dns-stock.com/my-ip.php' as primary check ip url
#
# dns stock update url syntax
# http://dyndns.dns-stock.com/?hostname=<domain>&username=<username>&password=<pass>&myip=<ipaddr>
#
# use cron to trigger (suggested every minute) e.g. '* * * * * ~/dnsstock_update.sh'
#
# $tmpdir
# is used for 'dnsstock_update.cache' and 'dnsstock_update.log' files
# omit trailing '/'

domain=''
username=''
password=''
checkipurl_1='dyndns.dns-stock.com/my-ip.php'
checkipurl_2='ipv4.whatismyv6.com'
tmpdir='/tmp'

# parse IPv4 for $chechipurl_1
ipaddr=$(wget -q -O - $checkipurl_1)
# check if wget returned != 0
if [ $? != 0 ]; then
  # parse IPv4 for 'ipv4.whatismyv6.com'
  ipaddr=$(wget -q -O - $checkipurl_2 | grep -iohP '(?<=\x3e)([0-9]+\.){3}[0-9]+(?=\x3c)')
  # check if wget returned != 0
  if [ $? != 0 ]; then
    exit 1
  else
    checkipurl_use='(2)'
  fi
else
  checkipurl_use='(1)'
fi

# exit 0 if $ipaddr is cached (= didn't change)
if [ -e $tmpdir/dnsstock_update.cache ] && [ $(cat $tmpdir/dnsstock_update.cache) = $ipaddr ]; then
  exit 0
fi

# check if IP valid (>255 check and IP syntax check)
if expr "$ipaddr" : '[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*$' >/dev/null; then
  for i in 1 2 3 4; do
    # >255 check
    if [ $(echo "$ipaddr" | cut -d. -f$i) -gt 255 ]; then
      # write log entry
      echo "$(date '+%Y-%m-%d %H:%M:%S')   FAIL$checkipurl_use: IPv4 invalid: $ipaddr (>255 check failed)." >> $tmpdir/dnsstock_update.log
      exit 1
    fi
  done
  # update dns
  success=$(wget -q -O - "http://dyndns.dns-stock.com/?hostname=$domain&username=$username&password=$password&myip=$ipaddr")
  if [ ! -z $update ]; then
    # write log entry
    echo "$(date '+%Y-%m-%d %H:%M:%S')   FAIL$checkipurl_use: dns stock server returned error." >> $tmpdir/dnsstock_update.log
    exit 1
  fi
  # update dnsstock_update.cache
  echo $ipaddr > $tmpdir/dnsstock_update.cache
  # write log entry
  echo "$(date '+%Y-%m-%d %H:%M:%S')   SUCCESS$checkipurl_use: IPv4 valid and updated: '$ipaddr'." >> $tmpdir/dnsstock_update.log
  exit 0
else
  # write log entry
  echo "$(date '+%Y-%m-%d %H:%M:%S')   FAIL$checkipurl_use: IPv4 invalid: '$ipaddr' (IP syntax check failed)." >> $tmpdir/dnsstock_update.log
  exit 1
fi

exit 0
