#!/usr/bin/perl -w
use strict;
use LWP;
#
# Post paramethers to dlink ip phones DPH-120 and DPH-140 by igor@spb.edu
#

# change it to your default
my ( $uname, $upassword ) = ('default_name','default_password');

my $tag_file = "act.tag";
my $mac_pat = '(?:[\dA-F][\dA-F]\.){5}[\dA-F][\dA-F]';
my $debug = 1;

sub debug { print STDERR "# ", (join " ",@_), "\n" if $debug; }
sub usage {
  print STDERR
    "Usage:\n$0 {\$ip,\$url} tz=3 pt2=4\n$0 {\$ip,\$url} \$file [-r] [-i]\n";
  exit;
}
my %f;

my ($url, $ip) = ('','');

my $ua = LWP::UserAgent->new;
sub post ( $ $ ) {
  my ( $href, $data ) = ( $_[0], $_[1] );
  debug "post: $url/$href", $data;
  my $req = HTTP::Request->new("POST" => "$url/$href");
  $req->referer("$url/$href");
  $req->authorization_basic('','');
  $req->content_type('application/x-www-form-urlencoded');
  $req->content($data);
  my $res = $ua->request($req)->as_string;
  return $res if $res !~ m#^HTTP/1.1 401 #;
  $req->authorization_basic($uname, $upassword);
  $res = $ua->request($req)->as_string;
  sleep 1;
  return $res if $res =~ m#^HTTP/1.1 200 #;
  debug $res;
  return $res;
}
sub garbage ( $ ) {
  local $_ = $_[0];
  s/&nbsp;/ /gm; s/[ \t]+/ /gm; s/.*?<body/<body/gm;
  s/<[^<>]*?>/<>/gm; s/ *<[<> ]*> */<>/gm; return $_;
}

########
# MAIN #
########
my %tags;
my $href = '';
open I, $tag_file or debug "Can't open $tag_file $!" and exit;
while (<I>) {
  chomp; next if /^[#;]/;
  if ( /^\[([\w\.]+)\]/ ) { $href = $1; next; }
  /^(\w+)=(.*)/ and push @{ $tags{$href} }, $1;
}
close I;

my %k;
# Get data
foreach my $arg ( @ARGV ) {
  if ( $arg =~ /^-(\w)(.*)/ ) { $f{$1}=$2; next; }  # flag
  if ( $arg =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/ ) { $ip = $arg; next; }
  if ( $arg =~ /^(\S+)=(.*)/ ) { $k{$1} = $2; next; }
  open I, $arg or die "Can't read from $arg $!";
  while ( <I> ) {
    next if /^[#;]/;
    my ( $key, $value ) = (/^(\S+)=(.*)/) or debug "Err: $_" and exit;
    $value =~ s{ \$([\w\-]+)}{ defined $k{$1} ? $k{$1} : $1 }gex;
    $k{$key} = $value;
  }
  close I;
}
usage unless $ip;
$url = "http://$ip:9999";
post "initcf.htm", '' and exit if defined $f{'i'};  # -i reinit
foreach my $href ( keys %tags ) {
  my @d;
  foreach ( @{ $tags{$href} } ) { defined $k{$_} and push @d, "$_=$k{$_}"; }
  $#d >= 0 and post $href, join '&', @d, "button=bntSubmit";
}
post "restart.htm", '' if defined $f{'r'}; # -r restart