#!/usr/local/bin/perl -w

#  mutt-ph-query.pl v0.1
#
#  Mutt external query program for ph/qi
#
#  Jay Kreibich, Research Programmer, CCSO, UIUC.
#  jak@uiuc.edu


require 5.002;

use strict;
use Socket;


my( $remote, $port, $iaddr, $paddr );

my( $query, $line, $code, $line_num, $email_domain );
my( $current, $c_alias, $c_email, $c_name, $c_title, $c_curriculum );


$remote = 'ns.uiuc.edu';
$port = 105;
$email_domain = 'uiuc.edu';

sub PrintEntry
{
	my( $alias, $email, $name, $title, $cur ) = @_;
	my( @name, $name_part );

	@name = split(' ', $name );
	$name = '';
	foreach $name_part ( @name )
		{ $name .= "\u$name_part "; }

	if( $email )
	{
		if( $alias )
			{ $email = "$alias\@$email_domain"; }
	}
	else
		{ $email = "--no-email-address--"; }


	if( not $title )
	{
		if( $cur )
			{ $title = "Curriculum: $cur"; }
		else
			{ $title = "no title/curriculum given"; }
	}

	print STDOUT "$email\t$name\t$title\n";
}



if( @ARGV == 0 ) { die "Usage: $0 <alias>\n"; }

$query = $ARGV[0];

$iaddr = inet_aton( $remote ) or die "Could not lookup host: $remote";
$paddr = sockaddr_in( $port, $iaddr );

socket( SOCK, PF_INET, SOCK_STREAM, 0) or die "socket: $!";
connect( SOCK, $paddr ) or die "connect: $!";

select (SOCK); $| = 1; select(STDOUT);

print SOCK "query $query return alias email name pretty_name title curriculum\r\n";



$line = <SOCK>;
( $code, $current ) = split(':', $line);
print STDOUT $current;
if( $code >= 200 ) { exit; }


$current = 1;
$c_alias = '';
$c_email = '';
$c_name = '';
$c_title = '';
$c_curriculum = '';

while( $line = <SOCK> ) 
{
	chomp $line;
	( $code, $line_num ) = split(':', $line);
	last if( $code >= 200 );
	next if( $code != -200 );

	if( $line_num != $current )
	{
		PrintEntry $c_alias, $c_email, $c_name, $c_title, $c_curriculum;

		$current = $line_num;
		$c_alias = '';
		$c_email = '';
		$c_name = '';
		$c_title = '';
		$c_curriculum = '';
	}


	$c_alias = $line if( $line =~ s/-200:.*\balias: // );
	$c_email = $line if( $line =~ s/-200:.*\bemail: // );
	$c_name = $line if( $line =~ s/-200:.*\bname: // );
	$c_name = $line if( $line =~ s/-200:.*\bpretty_name: // );
	$c_title = $line if( $line =~ s/-200:.*\btitle: // );
	$c_curriculum = $line if( $line =~ s/-200:.*\bcurriculum: // );
}


if( $code == 200 )
	{ PrintEntry $c_alias, $c_email, $c_name, $c_title, $c_curriculum; }


print SOCK "quit\r\n";
close( SOCK );

exit;


