#!/usr/bin/perl -w

use strict;

use Net::Telnet;

package nms;

use base 'Exporter';
our @EXPORT = qw(ios_waitprompt ios_enable ios_login ios_connect ios_close);

my $iosprompt = '/[^\s]+[#>]/';

sub ios_waitprompt($) {
	my ($t) = @_;

	#while ($t->getline) {
	#	print "Line: $_\n" if $_;
	#}

	my ($prematch, $match) = $t->waitfor($iosprompt);
	#print "PRE: $prematch\nM: $match\n";
}

sub ios_enable {
	my ($t, $enablepass) = @_;

	print STDERR "Enabling...\n";
	my @lines = $t->print("enable");
	if ($enablepass) {
		$t->waitfor('/Password: /');
		$t->print($enablepass);
	}
	ios_waitprompt($t);
}

sub ios_login($$$) {
	my ($t, $user, $pass) = @_;

	print STDERR "Waiting username\n";
	my ($prematch, $match) = $t->waitfor('/Username:\s{0,}/');
	print STDERR "Sending username\n";
	$t->print($user);
	print STDERR "Waiting password\n";
	($prematch, $match) = $t->waitfor('/Password: /');
	print STDERR "Sending password\n";
	$t->print($pass);

	ios_waitprompt($t);
}

use Data::Dumper;

sub ios_getroute {
	my ($t, $net) = @_;

	my @output = $t->cmd("show ip route".($net ? " $net" : ''));
	
	print Dumper(@output);
	foreach (@output) {
		return 0 if $_ =~ /^% Network not in table/;
	}

	return 1;
}

sub ios_connect {
	my ($host, $user, $pass, $enablepass) = @_;

	my $t = new Net::Telnet(Timeout => 15,
				Prompt => $iosprompt);
	$t->dump_log("/tmp/ios.log");
	$t->open($host);
	ios_login($t, $user, $pass);
	ios_enable($t, $enablepass) if $enablepass;
	$t->cmd("terminal length 0"); # Don't use the pager

	return $t;
}

sub ios_close($) {
	my ($t) = @_;

	$t->print('quit');
	$t->close;
}

