#!/bin/sh -e
# Searches the specified substring in address book for emacs-easypim
# Michael Pozhidaev <msp@altlinux.org>
# Date: 2011-03-21;

THIS="${0##*/}"

if [ "$1" == '--help' ]; then
    cat <<EOF
$THIS: searches the specified substring in address book for emacs-easypim utility

Usage:
    emacs-easypim-find [--files|--title] the_string_to_search

--files - print absolute name of matching files;
--title - print the name (without directory) of the first matching file. 

For proper work of this tool environment variable \$EASYPIMDIR must have non empty value.
EOF
    exit 0
fi

if [ "$1" == '--files' ]; then
    TYPE=files
    STRING="$2"
elif [ "$1" == '--title' ]; then
    TYPE=title
STRING="$2"
else
    TYPE=normal
    STRING="$1"
fi

if [ -z "$EASYPIMDIR" ]; then
    echo "$THIS:error:directory EASYPIMDIR is not set" >&2
    exit 1
fi

if [ -z "$STRING" ]; then
    echo "$THIS:the string to search is not specified" >&2
    exit 1
fi

exec 2> /dev/null

grep -F -r -l "$STRING" "$EASYPIMDIR" | 
while read l; do
    if [ "$TYPE" == files ]; then
	realpath "$l"
    fi
    if [ "$TYPE" == title ]; then
	basename "$l"
    fi
    if [ "$TYPE" == normal ]; then
echo "$(basename "$l"): $(grep -F -h "$STRING" "$l" | head -n 1)"
    fi
done | sort
