#!/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 $switch_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 "ssh command is $command\n";
#print "switch command is $switch_cmd\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);

# BUG here should allow for unknown host keys...

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

# first prompt will be "some name>"
$patidx = $exp->expect($timeout, '>');

# enable mode
$exp->send( "enable\n" );

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

# send our command
$exp->send( "$switch_cmd\n" );

my $out = "";
$patidx = $exp->expect($timeout,
		       [
			qr/.*\(y\/n\).*/i,
			sub{
			  my $self = shift;
			  $out .= $self->before();
			  $self->send( "y\n" );
			  exp_continue;
			}
		       ],
		       [
			qr/y\r\n/i,
			sub{
			  exp_continue;
			}
		       ],
		       [
			qr/access will be blocked/i,
			sub{
			  exp_continue;
			}
		       ],
		       [
			qr/transferred\.\.\./i,
			sub{
			  exp_continue;
			}
		       ],
		       [ 
			qr/\W+.*--More--.*/i,
			sub {
			  my $self = shift;
			  $out .= $self->before();
			  $self->send( "\n" );
			  exp_continue;
			}
		       ],
		       [
			qr/\r\s+\r/i,
			sub{
         		  my $self = shift;
			  $out .= $self->before();
			  exp_continue;
			}
		       ],
		       [ 
			qr/.*#/i, 
			sub { 
			  my $self = shift;
			  $self->send( "quit\n" );
			}
		       ],
		      );

$exp->soft_close();

print "$out\n\n";
