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

=head1 NAME

  mpadq - mutt (pilot|palmpilot|palm) addressbook query
  From:  http://www.quiet.demon.co.uk/software/mpadq

=head1 SYNOPSIS

  mpadq [query_string]

  In .muttrc: set query_command="mpadq %s"

=head1 DESCRIPTION

  This is meant to be called using the external query facility
  of the mutt(1) mail user agent, although it could also be useful
  for command line invocation.

  It does a case-insensitive regular expression match on the
  first name, last name, company and email fields of all
  addressbook entries, and returns matching results back in
  the format mutt expects, with the company addressbook
  field used in the 'optional information' position.

  Records that contain more than one email address produce
  one line of output for each address.

=head1 RETURN VALUE

  Returns 0 when matching records found, 1 otherwise.

=head1 FILES

  ${HOME}/.jpilot/AddressDB.pdb - the raw pilot addressbook database.

  Change the script to point to wherever yours lives.

=head1 SEE ALSO

  mutt(1), pilot-link(1), the PDA::Pilot module.

=head1 BUGS

  Craig Sebenik (craig@netapp.com) reports truncation of email addresses
  longer that about 25 characters under Solaris.  I haven't been able to
  reproduce this on my system (Linux), but if it bites you let me know.

=head1 AUTHORS

  originally written by Lucas Maneos <lm@quiet.demon.co.uk>
  bug fixes by Craig Sebenik <craig@netapp.com>

=cut

use strict;
use PDA::Pilot;

my $ABFILE="$ENV{'HOME'}/.jpilot/AddressDB.pdb";
my ($ab, $rec, $nr, $i, $addr, $tmp, @list);
my ($fname, $lname, $email, $company, $name);
my $qry=shift||"";

if ( ! -r $ABFILE ) {
	if ( ! -e $ABFILE ) {
		die "File \"$ABFILE\" does not exist.\n"
	}
	die "Cannot read \"$ABFILE\".\n"
}

$ab=PDA::Pilot::File::open($ABFILE) || die("Can't open $ABFILE: $!\n");
$nr=$ab->getRecords();

print "Searching database for '$qry' ... $nr entries ... ";

for ($i=0; $i<$nr; $i++) {
	$rec=$ab->getRecord($i) || next;
	$addr=PDA::Pilot::Address::Unpack($rec);
	$email="";
	for (3 .. 7) {  # any of the 'phone' fields could be an email address
		$tmp=$addr->{entry}[$_];
		next if (!defined($tmp));
		if ($tmp =~ /\@/) {
			$email.=$tmp." ";
		}
	}
	next if ($email !~ /\@/);
	$email=~s/[\015\012]+/ /g;
	$lname=$addr->{entry}[1];
	$lname="" if (!defined($lname));
	$fname=$addr->{entry}[0];
	$fname="" if (!defined($fname));
	$company=$addr->{entry}[2];
	$company="" if (!defined($company));
	foreach (split(/ +/, $email)) {
		$tmp="$lname $fname";
		$tmp=~s/^ *//;
		$tmp=~s/ *$//;
		$tmp=~s/ +/ /g;
		$tmp=$company if ($tmp eq "");
		$name="$_\t$tmp\t$company";
		$name=~s/[\015\012]+/ /g;
		push @list, $name if ($name =~ /$qry/i);
	}
}
$ab->close();

my $nmatch=scalar(@list);
print "$nmatch match", ($nmatch==1)?"\n":"es\n";
foreach (@list) {
	print "$_\n";
}
exit !$nmatch;

