#!/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
#
# modified by Jason Lindquist <linky@see.figure1.net> 6/3/1998
# to search multiple ph servers


# Change this to whatever & wherever you call your ph binary

$PH = "ph";


# List your domains

@domains = ("qualcomm.com", "uiuc.edu", "figure1.net");


# @returns contains one field to use as a comment for entries from
# the corresponding $domain[]

@returns = ("extension", "phone", "callsign");


# This gets prepended to each @domain entry to get the hostname
# of the ph server

$phhostname = "ns.";

# Trap misusage

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


$count = 0;
for( $i=0; $i <= $#domains; $i++ ) {
  open (QUERY, "$PH -s ${phhostname}${domains[$i]} '@ARGV' return name alias ${returns[$i]}|");
  @reply = <QUERY>;

  # Ignore an error from one domain and continue to the next.

  if ($reply[0] !~ /----------/)
  {
     next;
  }
  
  # Slurp information out of what we got back

  @thisresult = ();
  $name = "";
  foreach $line (@reply)
  {
  
    # Catch the entry separator

    if( $line =~ /^--*-$/ ) {
      if( $#thisresult >= 0 ) {
        # Original: $email."\t".$pretty."\t".$comment;
        if( $name eq "" ) {
  	  $name = "noname_${count}";
        }
        $RESULT{$name} = join( "\t", @thisresult );
        $count++;
      }
      @thisresult = ();
      $name = "";
      next;
    }

    # Append $count to the name, since we key the hash on $name,
    # and the same name might appear in more than one domain
    # ("jason lindquist" appears in some way in each of the three
    # example domains)

    if ($line =~ /name:/)
    {
      $line =~ /name: (.*)/;
      $name = $1.${count};
      $thisresult[1] = $1;
    }

    # email address is generally <alias@domain>
    
    if ($line =~ /alias:/)
    {
      $line =~ /alias: (.*)/;
      $thisresult[0] = $1."\@".$domains[$i];
    }

    # Pick up the comment field

    if ($line =~ /${returns[$i]}/)
    {
      $line =~ /${returns[$i]}: (.*)/;
      $thisresult[2] = $1;
      if( $thisresult[2] =~ /Not present in entry./ ) {
        $thisresult[2] = "<No ${returns[$i]}>";
      }
    }
  
  }
}

# Dump our results back to mutt

print $count." entries returned\n";

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

exit (0);
