#!/usr/bin/perl

use Encode;
use Net::SSLeay qw(get_https post_https make_headers make_form);
use MIME::Base64;

if ($#ARGV != 2) {
  print STDERR "usage: perl updateip.pl username password command\n";
  print STDERR "command = {newip|offline}\n";
  exit 0;
}

($user, $pass, $command) = @ARGV;
if ($command ne "newip" && $command ne "offline") {
  print STDERR "command must be \"newip\" or \"offline\"\n";
  exit 0;
}


$htmlfile1 = "/tmp/ipcheck1.html";
$htmlfile2 = "/tmp/ipcheck2.html";

# get 1st page
($page) = get_https('www.atnifty.com', 443, '/ddns/p13.php');
&create_file($htmlfile1);

# read it
open (IN, $htmlfile1) or die "what??\n";

$status = 0;
$mode_count = 0;

while (<IN>) {
  &get_form_information($_);
}

close IN;

# some variables
#$command = "newip"; # use this to update IP address
#$command = "offline"; # use this to disable dinamic DNS

if ($action =~ /^(.+?)(\/.+)$/) {
  $post_url = $1;
  $post_dir = $2;
} else {
  print STDERR "bad action : $action\n";
  exit 0;
}

# post values
($page, $response, %reply_headers) =
  post_https($post_url,
      443,
      $post_dir,
      make_headers('Authorization' =>
        'Basic ' . MIME::Base64::encode("$user:$pass",'')),
      make_form(
        ipaddress => $valuemap{"ipaddress"},
        nifty_id => $valuemap{"nifty_id"},
        update => $command,
        valid => $valuemap{"valid"}));

print "response = $response\n";

&create_file($htmlfile2);

exit 0;

#### subr

sub create_file($) {
  my $filename = shift;

  open(OUT, ">$filename") or die "cannot create $filename\n";
  binmode OUT;
  $octets = decode("shift-jis", $page);
  $euc = encode("euc-jp", $octets);
  print OUT $euc;
  close OUT;
}

sub get_form_information($) {
  my $tmp = shift;

  if ($status == 0) {
    if ($tmp =~ /^<form/) {
      $status = &found_form($tmp);
    }
    return;
  }

  if ($status == 1) {
    $status = set_value($tmp);
    return;
  }
}

sub found_form {
  my $tmp = shift;

  if ($tmp =~ /action=\"https:\/\/(.+?)\"/) {
    $action = $1;
    return 1;
  }
  print STDERR "cannot set action\n";
  return 0;
}

# map some keys to values
sub set_value {
  my $tmp = shift;

  if ($tmp =~ /javascript/) { # end of form
    $mode_count = 1;
    return 0;
  }

  if ($tmp =~/^<input\s+type=/) {
    if ($tmp =~ /name=\"(.+?)\"\s+value=\"(.*?)\"/) {
      if ($mode_count == 0) {
        $valuemap{$1} = $2;
      }
    }
  }

  return 1;
}
