#!/usr/bin/perl -w
#
# muttph -- query program for mutt using Net::PH.
# Rich Lafferty <rich@alcor.concordia.ca>
#
# This program is free software; you can redistribute and/or modify it under
# the same terms as Perl itself (although the author is particularly fond of
# the Artistic License, he'll tolerate the GPL too).
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# 
# To use, add to your muttrc (one line):
#
# set query_command = 
#   "/path/to/muttph '%s' phserver namefield emailfield [otherfield1 [otherfield2..]]"
#
#  where phserver is the name of your PH server
#        namefield is the field which contains names
#        emailfield is the field which contains email addresses
#        otherfield1 etc. are fields which you wish returned in the query
#            for informational purposes.
#
#  For example, I use
#   "muttph '%s' phone.concordia.ca name email phone dept title"
#
# If you get an error like "Can't locate Net/PH.pm in @INC", then you need
# to install Net::PH, which is part of the libnet bundle:
#
# $ perl -MCPAN -e'install Net::PH'
#
# Querying is documented in the mutt manual, but you've already read that,
# so you knew that. :-) 

require 5.004;
use strict;
use Net::PH;
my $version = "0.2";

my ($query, $phserver, $namefield, $emailfield, @otherfields) = @ARGV;

my $ph = Net::PH->new($phserver,
		      Port    => 105,
		      Timeout => 120,
		      Debug   => 0);

unless ($ph) {
  print qq(muttph $version: Connection to $phserver failed.\n);
  exit 1;
}

# Ask PH server
my $q = $ph->query({ name => "$query" },
		   [$namefield, $emailfield, @otherfields]);

if (@{$q}) {

    print qq(muttph $version: Results for "$query" from $phserver\n);

    foreach my $handle (@{$q}) {
	print ${$handle}{$emailfield}->text . "\t";

# Uncomment this if your PH server returns names in the format "SMITH JOHN"
# and you want to send mail to John Smith rather than SMITH JOHN. Of course,
# this breaks on anything more complex than LASTNAME FIRSTNAME, but it saves
# having to retype them *all* to make them look pretty. :-)
#
        my ($lastname, $firstname) = split(" ",${$handle}{$namefield}->text,2);
        $lastname = ucfirst(lc($lastname));
        $firstname = ucfirst(lc($firstname));
        print "$firstname $lastname\t";

	# Comment this out if you've uncommented the bit above.
#       print ${$handle}{$namefield}->text . "\t";

	# Include other fields
	foreach my $field (@otherfields) {
	    my $entry = ${$handle}{$field}->text;
            print "$entry ";
        }
    print "\n";
  }
}
else {
     print qq(muttph $version: No results found for "$query" from $phserver\n);
}




