#!/usr/local/bin.sun4/perl

$DEBUG=0;

my $base;
($base = $0) =~ s#/.*/([^/]+)$#$1#; 

open(DEBUG, $DEBUG == 0 ? ">>/dev/null" : ">>/dev/stderr");

## pattern to grep for, command to run and menufile to look in.
if ($base eq 'con') { $patt="r?telnet"; $comm="runsocks telnet"; $menu="consoles" }
if ($base eq 'ssh') { $patt=$comm=$menu="ssh";}
if ($base eq 'scp') { $patt=$menu="ssh"; $comm="scp";}

## Arrays one per command type, single flag vs flag with option.
%args = (
	ssh => [qw/nAaXxtTvVPqfCNg462S liecmpLRo/],
	scp => [qw/pqrvC46 SPci/],
	con => [qw/ /],
);

## add ' -' to each arg.
for my $k (keys %args) {
  for my $t (0..1) {
    $args{$k}[$t] = ' -' . (join' -',split'',$args{$k}[$t]);
  }
}

$s=0; $cmp="";

for $i (0..$#ARGV) {
  ## '--' to stop processing cmdline args, and pass the rest. Useful if 
  ## ssh-ing in to run a command.
  if ($ARGV[$i] eq '--') { $end.= join' ',@ARGV[($i+1) .. scalar @ARGV]; last; }
  if ($s) {$cmp.=$ARGV[$i]." "; $s=0; next;}
	print DEBUG "->> $ARGV[$i]\n";
  if (mindex($args{$base}[0],$ARGV[$i])) {$cmp.=$ARGV[$i]." "; next;} 
  elsif (mindex($args{$base}[1],$ARGV[$i])) {$cmp.=$ARGV[$i]." ";$s=1;next;} 
  if (!$h) { $h=$host=$ARGV[$i]; next;}
  else { warn "Unknown arg $ARGV[$i]. If it's scp, I give up, otherwise try prefixing with '--' "; }
  $end.=" $ARGV[$i]";
}
$cmp=~s/\ $//g; 

print DEBUG "Read Host = \"$host\" ";
print DEBUG "init cmd params = \"$cmp\", tail bit =\"$end\"\n";

$men="/home/system/logs/internet/docs/openwin-menu-$menu";

open(A,$men);

$host="Console - ".$host if ($menu eq "consoles");

while (<A>) { 
  if (/.*"$host".*/) {
    if (/gateb/) { socks_env(); }
    s/.*-e *$patt *([\d\. ]+)[\r\n]+/$1/e; $h=$1; #print "$_ ";
  }
}

if ($cmp) {$cmp.=" ";}

print "/usr/local/bin.sun4/$comm $cmp$h $end"; $ENV{SOCKS_SERVER} ? print " ($ENV{SOCKS_SERVER})\n" : print "\n";
	print "--> exec /usr/local/bin.sun4/$comm $cmp$h $end\n";
    exec("\n/usr/local/bin.sun4/$comm $cmp$h $end\n");

close(A);
close(DEBUG);
exit;

sub socks_env {
	$ENV{SOCKS_SERVER}="gateb";
	$ENV{LD_LIBRARY_PATH}="/tool/local/lib/";
	$ENV{SOCKS5_SHLIB_RUNPATH}="/tool/local/lib/";
	$ENV{LD_PRELOAD}="/tool/local/lib/libsocks5_sh.so";
}

sub mindex { return index($_[0],$_[1]) + 1; } # just so '0' is failed.
