#!/usr/local/bin/perl5

use Socket;

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

($termserver,$modem,$command)=@ARGV;

if ( $termserver eq "" || !($modem =~ /[0-9]+/) || !($command =~ /AT/) ) {
    print "Usage: pmmodem <termserver> <modem port> <modem command>\nExample: pmmodem ts-1 6 ATI6\n";	
    exit(0);
}

$password="PASSWORD";

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("attach S$modem\n");
if (chat::expect(5,
		 "Couldn't configure attach",0,
		 "Connected -",1)) {
    print "Connected to modem, sending \"$command\".\n";
    chat::print("$command\r\n");
    print &listenr(5,"(OK|ERROR)");
    chat::print(sprintf("%c",29));
} else {
 	print "Modem is busy.\n"
}

if (chat::expect(5,">",1)) {
#    print "Back at command prompt.\n";
} else {
    die "Couldn't get back out of modem mode!";
}

chat::print("quit\n");
    
#print "Closing connection to $termserver\n";
chat::close($net);

## 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
                );
}

