#! /bin/ksh
#
# -*-sh-*-
#
#     m_gnomecard - GnomeCard Address book module for lbdb
#     Copyright (C) 2000 Rick Frankel <rick@rickster.com>
#                   2000-2005 Roland Rosenfeld <roland@spinnaker.de>
#
#     This program is free software; you can redistribute it and/or modify
#     it under the terms of the GNU General Public License as published by
#     the Free Software Foundation; either version 2 of the License, or
#     (at your option) any later version.
# 
#     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.  See the
#     GNU General Public License for more details.
# 
#     You should have received a copy of the GNU General Public License
#     along with this program; if not, write to the Free Software Foundation,
#     Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301,, USA.
#
# $Id: m_gnomecard.sh.in,v 1.9 2009/06/11 10:56:22 roland Exp $
#

prefix=/usr/local
exec_prefix=${prefix}
libdir=/usr/local/lib/lbdb
AWK=/usr/bin/awk

rcfile=$HOME/.gnome/GnomeCard

m_gnomecard_query ()
{
    if [ -z "$GNOMECARD_FILES" ]
    then 
	if [ -r "$rcfile" ]
	then
	    GNOMECARD_FILES=`\
		$AWK 'BEGIN {FS="="; infile=0} \
		      /^\[.*\]/ {infile=0} \
		      /^\[file\]/ {infile=1} \
		      infile && /^open=/ {print $2}' \
		    < $rcfile`
	fi
	if [ -z "$GNOMECARD_FILES" ]
	then
	    GNOMECARD_FILES="$HOME/.gnome/GnomeCard.gcrd"
	fi
    fi
    
    for file in $GNOMECARD_FILES
    do
	if [ $file = ${file#/} ]
	then
	    file=$HOME/$file
	fi

	if [ -f $file ]
	then
	    $AWK 'BEGIN {FS=":"; RS="\r\n"; name=""} \
		  /^END:VCARD/ {name=""} \
		  /^FN[:;]/ {name=$2} \
		  name!="" && /^EMAIL;/ {email=$2; \
					 type=substr($1,7); \
					 printf ("%s\t%s\tGC:%s\n", \
						 email, name, type) }' \
            < $file | grep -ia "$@" || :
	fi
    done
}
