#!/usr/bin/perl -w  
#               -w ワーニングを出す
use strict; # 宣言した変数以外を使えなくする

my $niftyid="NIFTYID";
my $niftypass="NIFTYPASSWROD";

my $file="/usr/local/bin/ddns4nifty/ipaddr.txt";
my $update="/usr/local/bin/ddns4nifty/update.log";
my $no_update="/usr/local/bin/ddns4nifty/no_update.log";
my $wget;
my $ipaddr;
my $valid;
my $oldipaddr;
my $sec;
my $min;
my $hour;
my $mday;
my $mon;
my $year;
my $wday;
my $yday;
my $isdst;
my $tt;
my $null="";

$| = 1;   # ゼロ以外が代入されると出力をバッファリングしなくなる。



# ########################
$wget = `wget --no-check-certificate -O- -q https://www.atnifty.com/ddns/p13.php`; # メッセージを表示しないに戻す
#print "debug  wget p13.php\n"; # 確認用の文を出力


$wget =~/[0-9]+(\.[0-9]+){3}/; # IPアドレスとのマッチパターン
$ipaddr = $&;  # マッチしたIPアドレスを入力
#print "Debug get ip address=$ipaddr\n"; # 確認用の文を出力

$wget =~/name="valid" value="[a-zA-Z0-9]+"/;  # validの部分を探す(マッチ)
$valid = $&;   # マッチした部分を入力
$valid =~s/name="valid" value="//;  # 値の前の部分を除去
$valid =~s/"//;    # 値の後ろの部分(")を除去
#print "Debug finish  valid=$valid\n"; # 確認用の文を出力


# ###########################
open FH, "<",$file || die "Error: ipaddr.txt $!\n" ; #ファイルを入力で開く
$oldipaddr = <FH> # 記録されているIPアドレスを入力
close FH;
#print "Debug get old ip address\n"; # 確認用の文を出力


# ###########################
# get ipaddress error check  (2008/06/21 追加 )
#
 if ($ipaddr eq $null) {
      $ipaddr = $oldipaddr ;
      print "Debug get ip address error null  ";
      print "Debug ipaddress = oldipaddress"
  }


# ###########################
if($ipaddr eq $oldipaddr){
        open (OUT,">> $no_update");
$tt=time();
($sec, $min, $hour, $mday, $mon, $year,
    $wday, $yday, $isdst) = localtime($tt);
$year=$year+1900;
$mon=$mon+1;
print OUT $year,"/",$mon,"/",$mday,"   ",$hour,":",$min,":",$sec,"  "  ;
	print OUT "ip address is not changed:$ipaddr\n" ;  #IPアドレスに変更無し
        close(OUT);
#   print "Debug not change ip address\n"; # 確認用の文を出力
}


# ##########################
else{
        open (OUT,">> $update");
$tt=time();
($sec, $min, $hour, $mday, $mon, $year,
    $wday, $yday, $isdst) = localtime($tt);
$year=$year+1900;
$mon=$mon+1;
print OUT $year,"/",$mon,"/",$mday,"   ",$hour,":",$min,":",$sec,"  "  ;
	print OUT "ip addres is changed:$ipaddr\n" ;
        close(OUT);
	open FH,">",$file|| die "Error: ipaddr.txt $!\n" ;
	print FH "$ipaddr" ;
	close FH;


        $wget=`wget --secure-protocol=auto --no-check-certificate -O- -q --http-user=$niftyid --http-passwd=$niftypass --post-data="ipaddress=$ipaddr&nifty_id=&update=newip&valid=$valid"  https://gateway.nifty.com/service/g-way/ddns/nifty/secure/config/update.php`; # --secure-protocol=autoを追加した(2008/8/19)
#   print "finish change ip address\n"; # 確認用の文を出力

}