#!/usr/athena/bin/perl

use Socket;

# check usage
if ($#ARGV != 0) {
  print "Usage: $0 <username>\n";
  exit(1);
}

# read configuration file
die if (!open(INI, '/etc/ecat.conf'));
while(<INI>) {
  chop;
  @Fld = split('\s', $_);
  if ($#Fld < 0) {
  } elsif ($#Fld == 0) {
    $section = substr($Fld[0], 1, length($Fld[0]) - 2);
  } elsif ((@Fld = split(/=/, $_)) == 2) {
    $Fld[0] =~ s/\s//g;
    $Fld[1] =~ s/^\s//;
    $conf{$section, $Fld[0]} = $Fld[1];
  }
}
close(INI);
 
$status = ECATUserProfile(\%info, $conf{'profile','hostname'),
	$conf{'profile','port'), $ARGV[0]);

die "ECATUserProfile() failed, $status," if ($status>0);

foreach $key (keys %info) {
    print $key, "\t", $info{$key}, "\n";
}

exit(0);

##########################################################
############### subroutine ECATUserProfile ###############
##########################################################

sub ECATUserProfile {
    my($info, $server, $port, $user) = @_;
    my($server_addr, $server_name, @lines, $name, $value, @host);

# look up the server's IP address
    @host = gethostbyname($server);
    return($!=2) if ($#host<0);	# ENOENT -- actual error is h_errno
    $server_addr = @host[4];

# open a socket
    return($!) if (!socket(S, AF_INET, SOCK_STREAM, 0));

# form the server name (struct sockaddr_in) and connect socket to name
    $server_name = pack('S n a4 x8', AF_INET, $port, $server_addr);
    return($!) if (!connect(S, $server_name));

# give the user name to the server ("select" is used for easy flush)
    select(S);
    $| = 1;
    print "$user\n";
    select(STDOUT);

# read the ECAT user info
    while(<S>) {
	chop $_;
	($name, $value) = split(/\s+/,$_,2);
	last if ($name eq ".");
	$info->{$name} = $value;
    }

# close the socket
    close(S);

# finish up
    return(0);
}
