#!/bin/sh
# copyright (c) jose nazario (jose at monkey dot org), all rights
# reserved. this is NOT GPLd, it is available under a BSD style license.

# search, a small command line utility to grok through my PDF files
# and their indicies. props to bob for convincing me this could be done.

export INDEX=${HOME}/.index
export COMMAND="-i"
export VERBOSE=0
export COUNT=0

usage() {
	echo "usage: search [-v] <term> ?term? ..."
	exit
}

# ensure we have something to do
if [ $# -lt 1 ]; then
	echo "missing parameters"
	usage
fi

if [ ! -d ${INDEX} ]; then
	echo "cannot continue, missing index files."
	exit
fi

IDX_FILES=`ls -l ${INDEX}/*.idx | wc -l `

if [ 1 -ge ${IDX_FILES} ]; then
	echo "no index files, quitting"
	exit
fi

# build the egrep command
while [ $# -ge 1 ]; do
	if [ "-v" == $1 ]; then
		export VERBOSE=1
		shift
	else
		export COMMAND="${COMMAND} -e $1"
		shift
	fi
done

# actually search for stuff
echo "   matches\tfilename" 
for i in `ls ${INDEX}/*.idx`; do
	export COUNT=`egrep ${COMMAND} $i | wc -l`
	export FILENAME=`head -1 $i`
	# only print what has matches
	if [ 0 -eq ${COUNT} ]; then
		true
	else
		echo "${COUNT}\t${FILENAME}"
		if [ 1 -eq ${VERBOSE} ]; then
			head -10 $i | fmt -72
		fi
	fi
done
