#!/usr/bin/perl

use strict;
use warnings;
use diagnostics;

# requires the perl-Expect module.  find rpm of it in dag repository.
use Expect;

# need better parameter handling :-(
my $switch_ip = $ARGV[0];
my $show_cmd = $ARGV[1];

# read the ini file
# expect to see entries like:
# ip,user,password
my $inifile="/root/switch.ini";
my %ini;
open(INI,"$inifile") || die "failed to open $inifile";
while(<INI>){
  chomp;
  # allow comments
  next if /^\s*#/;
  # remove whitespace
  s/\s//g;
  # require three comma separated fields
  next if not /^(.*?),(.*?),(.*?)$/;
  if ( $1 eq $switch_ip ){
    $ini{switch} = $1;
    $ini{user} = $2;
    $ini{passwd} = $3;
  }
}
close(INI);

$ini{switch} or die "$0: did not parse $inifile...\n";

my $timeout = 10;
my $command = "ssh $ini{user}\@$ini{switch}";

print "command is $command\n";

my $exp = new Expect;
$exp->raw_pty(1);

$exp->spawn($command) or die "Failed to spawn $command: $!\n";

# normal
$exp->log_stdout(0);
# debugging
#$exp->exp_internal(1);

my $patidx = $exp->expect($timeout, 'password:');
print $exp "$ini{passwd}\n";

#this prompt will be "some name>"
$patidx = $exp->expect($timeout, '>');
print $exp "enable\n";


$patidx = $exp->expect($timeout, '#');
print $exp "$show_cmd\n";

my $out = "";
$patidx = $exp->expect($timeout,
		       [
			qr/$show_cmd\r\n/i,
			sub{
			  my $self = shift;
			  $self->set_accum($self->after());
			  exp_continue;
			}
		       ],
		       [ 
			qr/\W+.*--More--.*/i,
			sub {
			  my $self = shift;
			  $out .= $self->before();
			  print $self "\n";
			  exp_continue;
			}
		       ],
		       [
			qr/\r\s+\r/i,
			sub{
			  exp_continue;
			}
		       ],
		       [ 
			qr/#/i, 
			sub { 
			  my $self = shift;
			  print $self "quit\n"; 
			}
		       ],
		      );

$exp->soft_close();

print "$out\n";
