#!/usr/local/bin/perl
#
# mutt_ph_query.pl
# Really quick hack to format ph output into a format suitable for my
# patch to mutt for external address query.  Looks up name and email
# from a ph/qi database.
#
# Brandon Long (blong@fiction.net) 4/6/98
#
# Public Domain, nothing special here, no guaruntees, warranties,
# usefulness for a purpose, blah blah
#
# modified by Daniel Grobe Sachs <sachs@uiuc.edu> 4/14/98 to
# be better suited to UIUC ph server and email aliases

$PH = "ph";
$DOMAIN = "uiuc.edu";

if (!defined ($ARGV[0]))
{
  print STDERR "Usage: $0 <ph arguments>\n";
  exit (1);
}

open (QUERY, "$PH '@ARGV' return name pretty_name alias title|");
@reply = <QUERY>;
if ($reply[0] !~ /----------/)
{
  print "$0: $reply[0]";
  exit (1);
}

$state = 1;
$count = 0;
foreach $line (@reply)
{
  if ($state == 1)
  {
    $state = 2 if ($line =~ /----------/);
  } elsif ($state == 2)
  {
    if ($line =~ /name:/)
    {
      $line =~ /name: (.*)/;
      $name = $1;
      $state = 3;
    }
  } elsif($state == 3)
  {
    if ($line =~ /pretty_name:/)
    {
      $line =~ /pretty_name: (.*)/;
      $pretty = $1;
      $state = 4;
    }
  } elsif ($state == 4)
  {
    if ($line =~ /alias:/)
    {
      $line =~ /alias: (.*)/;
      $email = $1."@".$DOMAIN;
      $state = 5;
    }
  } elsif ($state == 5)
  {
    if ($line =~ /title:/)
    {
      $line =~ /title: (.*)/;
      $comment = $1;
      if( $comment =~ /Not present in entry./ ) 
      {
        $comment = "<no title>";
      }
      $RESULT{$name} = $email."\t".$pretty."\t".$comment;
      $state = 1;
      $count = $count + 1
    }
  }
}

print $count." entries returned\n";

foreach $i (sort keys %RESULT)
{
  print "$RESULT{$i}\n";
}

exit (0);
