#!/bin/bash
# -*-coding: latin-1-unix;-*-
#
# greptool -- Tool to grep various source code files
#
# Recursively grep for pattern in many source files in multiple directories.
#
# Copyright (C) 2007-2016.
#
# $Compile: ./greptool foo$
# $Maintained at: http://www.visualco.de$
# $Author: Andreas Spindler <info@andreasspindler.de>$
# $Writestamp: 2016-04-20 13:21:57$

scriptname=`basename "$0"`

Usage() {
    cat <<EOF 1>&2
USAGE
    $scriptname [-n FILESPEC -i -w] PATTERN [dirname]...
EOF
}

Help() {
    Usage
    cat <<EOF 1>&2

OPTIONS
    -n FILESPEC
         Find files matching the pattern. FILESPEC is applied to the whole
         pathname. Multiple patterns can be specified. Only '*', '?', and '[]'
         are allowed as metacharacters (see examples).

    -i   Ignore case distinctions in both the PATTERN and FILESPEC.

    -w   Match only at word boundaries. Word-constituent characters are letters,
         digits, and the underscore. The test is that the matching substring
         must either be
             - at the beginning of the line,
             - preceded by a non-word constituent character,
             - at the end of the line,
             - followed by a non-word constituent character.

    -h   Print this information.

The FILESPEC metacharacters  stand for their own. Braces and  the '.' character
are not  recognized to be special.  For example, "*.[ab]c*" matches  "x.ac" and
"y.bc" but not "z.a". The pattern "*htm"  finds only files ending in "htm", not
ending in "html". For details see the fnmatch library function.

The default FILEPSPECs include file types Assembler, C/C++, Perl, Python, Shell
scripts, makefiles. This script is maintained at <http://www.visualco.de>.

EOF
}

opts= optsinc=
for i in 'asm' 'inc' '[ch]' '[ch][px][px]' 'p[lmy]' 'sh' '[io]dl' 'm*k'; do
    optsinc="$optsinc --include=*.$i"
done
for i in 'txt' 'tex' 'pod'; do
    optsinc="$optsinc --include=*.$i"
done
for i in '*[Mm]akefile' '*Change[Ll]og' 'TODO' 'README' 'MANIFEST' 'MOTIVATION'; do
    optsinc="$optsinc --include=$i"
done
for i in 'svn-base' 'd'; do
    optsinc="$optsinc --exclude=*.$i"
done

while getopts 'win:vhH' opt; do
    case $opt in
        w) opts="-w $opts";;
        i) opts="$opts -i";;
        n) optsinc= opts="$opts --include=$OPTARG";;
        [hH]) Help; exit 0;;
        *) Usage; exit 1;;
    esac
done
shift $(($OPTIND - 1))          # correct the index so the next argument is $1
optre=$1; shift
dirnames=${*:-.}

[[ -z $optre ]] && { Usage; exit 1; }

GREP_OPTIONS="--color=auto --binary-files=without-match -rsnH"
GREP_COLOR="0;32"

export GREP_OPTIONS
export GREP_COLOR

for dir in $dirnames; do
    set -x
    grep $opts $optsinc -e "$optre" $dir
    set +x
done

# Local Variables:
# coding: iso-8859-1-unix
# fill-column: 79
# End: