#/usr/local/bin/perl
#----------------------------------------------------------------------
# variables to change

$Gconf_file = "/home/ashpool/go4gw/go4gw.conf"; # configuration file
$Gport=4324;                               # port THIS daemon is running on
$Ghost="ashpool.micro.umn.EDU";            # host THIS daemon is running on

#----------------------------------------------------------------------

&go4gw_main if (!defined($GnotServer));

sub go4gw_main {

# get command
$_ = <STDIN>; s/\r//; s/\n//;

($gw,$args) = /^(\w+)\s*(.*)$/ if (!/^$/);

open(CONF,$Gconf_file) || &Gabort("$Gconf_file: $!");
while(<CONF>) { 
     chop;
     next if /^#/ || /^$/;
     ($gateway,$user,$module,$title) = split(/:/);
     if ($gw eq '' && $title) { &Greply("1$title\t$gateway\t$Ghost\t$Gport"); }
     elsif ($gw eq $gateway) { &launch_gateway($user,$gateway,$module,$args); }
}

if ($gw eq '') { &Greply("."); exit; }
else { &Gabort("3No such gateway: $gw"); }

}
sub launch_gateway {
   local($user,$gateway,$module,$args) = @_;

   if ($user =~ /^\-?\d+$/) { $Guid = $user; }
   elsif ($user eq '') { $Guid = -2; }
   else {           
       ($n,$pw,$Guid) = getpwnam($user);
       if ($Guid eq '') { $Guid = "-2"; }
   }

  ($<,$>) = ($Guid,$Guid) unless $>;
   &Gabort("Can't load gateway: $module") if (! -e $module);
   require "$module";
   $main = "${gateway}_main";
   $Ggw = $gateway;
   &$main($args);
   &Greply(".");  # shouldn't really get here, but what the hack!
   exit;
}

#
# standard routines
#

sub Greply { print "$_[0]\r\n"; }

sub Gabort { print "3$_[0]\r\n.\r\n"; exit; }

sub GopenServer {

 local($server,$port) = @_;
 $sockaddr = 'S n a4 x8';
 (($name, $aliases, $type, $len, $saddr) = gethostbyname($server))
        || &Gabort("3Can't get address of: $server");
 $sin = pack($sockaddr, 2, $port, $saddr);
 socket(GSERVER, 2, 1, 0) || &Gabort("Can't create socket: $!");
 connect(GSERVER, $sin)   || &Gabort("Can't connect to server: $!");
 select(GSERVER); $| = 1; select(STDOUT); $| = 1;
}

sub GcloseServer {
  close(GSERVER);
}

sub Gsend { 
     print "send -> |$_[0]|\n" if (defined($Gdebug));
     print GSERVER "$_[0]\r\n"; 
}

sub Grecv { 
   local ($_); 
   $_= <GSERVER>; 
   s/\n$//;
   s/\r$//;
   print "recv -> |$_|\n" if (defined($Gdebug));
   return $_; 
}

sub Gsorry {

print<<EOF;

Sorry! You have selected information that cannot be delivered off
of campus due to restrictions.

   -- The Mole Hole Guardian

EOF

&Greply(".");
exit;

}

1;  # for require
