package H1::ZTEMSAN;
use warnings;
use strict;

use Net::Telnet;
use Data::Dump qw(dump);

sub hash {
	my $self = shift;
	my $args = {@_};

	warn "# info ", dump($args);

my $t = Net::Telnet->new( Timeout => 20, Port => 1123, Prompt => '/#/' );

$t->dump_log('/tmp/log') if $ENV{DEBUG};

warn "open";
$t->open( $args->{ip} );

$t->waitfor('/Login:/');
$t->print('root');
$t->waitfor('/Password:/');
$t->print('root');
#$t->waitfor('/>/');
#$t->print('en');
#$t->waitfor('/Please input password:/');
#$t->print('admin');
$t->waitfor('/#/');

warn "login OK";

my $port = "$args->{shelf}/$args->{slot}/$args->{port}";

sub command {
	my $command = shift;

	warn "# command $command\n";
	$t->print($command);

	my $out;
	while (1) {
		warn "waitfor";
		my($prematch, $match) = $t->waitfor('/(Press any key to continue \(Q to quit\)|#)/');
		$out .= $prematch;
		last if $match eq '#';
#		$t->put(" ");
		$t->print('');
	}

	warn "## out = [$out]";

	my $hash;
	my $section = '';
	my $last_line;
	foreach my $line ( split(/[\n\r]+/, $out) ) {
		warn "# $line\n";
		if ( $line =~ m/^(\S+.*?)\s+:\s+(\S+.*?)\s*$/ ) {
			my ($n,$v) = ($1,$2);
			$n =~ s/\(.+\)//;
			$hash->{ $section . $n } = $v;
			warn "## $n = $v\n";
		} elsif ( $line =~ m/^-+$/ ) {
			$section = $last_line . '.'
		}
		$last_line = $line;
	}

	warn "## hash = ",dump $hash;

	if ( $ENV{DEBUG} ) {
		my $path = $command;
		$path =~ s{\W+}{_}g;
		$path = "/tmp/dump.$path";
		open( my $fh, '>', $path ) || die "$path: $!";
		print $fh $out;
		close $fh;
		warn "DEBUG ",$path, " ", -s $path, " bytes\n";
	}

	return $hash;
}

our ( $row, $hash );

sub copy {
	my @what = @_ ? @_ : keys %$hash;
	foreach my $name (@what) {
		warn "# copy $name ", dump( $hash->{$name} ),$/;
		$row->{$name} = $hash->{$name};
	}
}

$hash = command "show adsl port $port";
copy;

$hash = command "show adsl port $port line-config";
copy;

$hash = command "show adsl port $port physical-table";
copy;

warn "# row = ",dump $row;

warn "logout";
$t->print('logout');
$t->waitfor('/:/');
$t->print('y');


} # sub
1;

