#!/bin/bash

function usage
{
    echo "usage: search [arguments] [options]"
    echo "arguments:"
    echo "         for text"
    echo "         in directory"
    echo "options:"
    echo "         -b | --include-binaries"
    echo "         -c | --case-sensitive"
    echo "         -s | --show-filenames-only"
    echo "         -n '*filter*'| --name-filter '*filter*'"
    echo "         -cmd | --show-command"
}

directory='.'
namefilter=''
binary=I
case=i
verbose=H
showcmd=false
while [ "$1" != "" ]; do
    case $1 in
    for | -f | --for )
        shift
        text=$1
        ;;
    in | --in | -i )
        shift
        directory=$1
        ;;
    -h | --help )
        usage
        exit
        ;;
    -b | --include-binaries )
        binary=
        ;;
    -c | --case-sensitive )
        case=
        ;;
    -s | --show-filenames-only )
        verbose=l
        ;;
    -n | --name-filter )
        shift
        namefilter="-name \"$1\""
        ;;
    -cmd | --show-command )
        showcmd=true
        ;;
    * )
        usage
        exit 1
    esac
    shift
done

# Build command string
cmd="find $directory $namefilter -type f -exec grep -$case$verbose$binary \"$text\" --color=auto -n {} \;"

# Show command string
if $showcmd; then
    echo "=========================================================================="
    echo $cmd
    echo "=========================================================================="
fi

# Execute the command
eval $cmd
