#!/usr/local/bin/perl5

use Socket;

require "/home/j/josh/opt/lib/chat2.pl" || die "Hey! $!";

($termserver,$modem)=@ARGV;

if ( $termserver eq "" || !($modem =~ /[0-9]+/)) {
    print "Usage: pmwatch <termserver> <modem port>\n";
    exit(0);
}

$SIG{'INT'}='handler';
$SIG{'TERM'}='handler';

sub handler {
    print "Shuttin' down..";
  chat::print("set debug 0x0\nquit\n");
  chat::close($net);

    $SIG{'INT'}='handler';
    $SIG{'TERM'}='handler';
}


$password="V1q2was5";

print "Connecting to $termserver, modem S$modem, command: \"$command\"\n";

$net=chat::open_port("$termserver",23);
if (! defined $net) { die "unable to open telnet connection! ($!)"; }

if (chat::expect(5,"ogin:",1)) {
#    print "login:\n";
    chat::print("!root\n");
} else {
    die "no login: prompt.";
}

if (chat::expect(5,"ord:",1)) {
#    print "password:\n";
    chat::print("$password\n");
} else {
    die "no password: prompt.";
}

$a=chat::expect(5,">",1,"Invalid",2);
if ($a==2) { die "Invalid password"; }
if ($a==1) {
#    print "Got command prompt\n";
} else {
    die "Couldn't get command prompt.";
}

chat::print("set console\n");
chat::print("set debug 0x75\n");

while(1) {
  chat::print("show S$modem\n");
  chat::expect(4,"Recvd",1);
  $this=&listenr(5,"$termserver");
    if ($this ne $last) { print $this; }
    $last=$this;
    sleep 3;
}

## Stuff from randall's GetWeather script.
sub listen {
        local($secs) = @_;
        local($return,$tmp) = "";
        while (length($tmp = &telnet_read($secs))) {
                print $tmp if $trace;
                $return .= $tmp;
        }
        $return;
}

sub listenr {
        local($secs,$regex) = @_;
        local($return,$tmp) = "";
        while (length($tmp = &telnet_read($secs))) {
                print $tmp if $trace;
                $return .= $tmp;
                last if $return =~ /$regex/i;
        }
        $return;
}

sub telnet_read {
        local($secs) = @_;
        &chat'expect($secs,
                '^\377[\375\376](.|\n)',
                q#&chat'print ("\377\374".$1); redo LOOP#,
                        # WON'T do these do/don't requests
                '^\377[\373\374](.|\n)', 'redo LOOP',
                        # ignore these will/won't changes
                '^\377\377', '"\377"',
                        # escaping the IAC
                '^\377(.|\n)', 'redo LOOP',
                        # ignoring these
                '^[^\377]+', '$&'
                        # return these
                );
}

