#!/bin/sh
# DynamicDNS

data_file="/dev/shm/log/oldip.dat"
dns_file="/dev/shm/log/dnsip.dat"
tmp_file="/dev/shm/log/.chkip.tmp"
log_file="/dev/shm/log/ip.log"
count_file=/dev/shm/log/count.dat

ng_file=/usr/local/bin/ipupdate/ng.dat

declare -i count
count=`cat $count_file`

declare -i ng
ng=`cat $ng_file`

# Read previous IP from data_file, and restore to oldip.
oldip=`cat $data_file`

# Download IP page to .chkip.tmp.
wget -q -O $tmp_file 'http://user:user@192.168.1.1/cgi-bin/main.cgi?mbg_webname=status'

# Get newip from .chkip.tmp
newip=`nkf -e $tmp_file | sed -n '84p' | sed -e "s/[<,>,/,td,nowrap,:,^M, ]//g"`

# Get present IP with Nslookup
dnsip=`nslookup asada.info | sed -n "6p" | sed -e "s/Address: //g"`

#Timer
count=$count+1
if [ $count -ge 6 ]
then
  flug=0

  # Compare new IP with previous IP.
  if [ $oldip != $newip ]
  then
    flug=1
  fi

  # Compare new IP with DNS IP
  if [ "$dnsip" != $newip ]
  then
    flug=2
  fi

  if [ "$dnsip" = "" ]
  then
    flug=0
    ng=$ng+1
    echo $ng > $ng_file
  fi

  # When not equal, renew IP.(Result is written over .chkip.tmp)
  if [ $flug -ne 0 ]
  then
    wget -q -O $tmp_file 'http://dyn.value-domain.com/cgi-bin/dyn.fcg?d=example.com&p=hogehoge&h=*&i='
  # Extract IP from .chkip.tmp, and write to chkip.dat.
    echo -n $newip > $data_file
    echo -n $dnsip > $dns_file
  # add log to /usr/local/bin/ipupdate
    status=`cat $tmp_file | grep "status"`
    echo `date '+%Y/%m/%d %T'` " [" $oldip "=>" $newip " , " $dnsip ","$flug" ] :" $status | tr "[:cntrl:]" "#" | sed -e "s/#//g" >> $log_file
    echo >> $log_file
    count=0
    ng=0
  fi
fi
echo $count > $count_file

# end
exit

