#!/bin/ksh
DUMMY=/tmp/mygrepsh_aj_$$

WARNING=""
RECURSE=""
while true; do
    if [ ""$1 = "-w" ]; then 
	WARNING="-w"
	shift	
    elif [ ""$1 = "-r" ]; then
	RECURSE="-r"
	shift
    elif [ ""$1 = "-h" ]; then
        echo 'Usage:   mygrep [-w] [-r] [-h] <searchstring> {<files>}'
	echo ''
	echo ' -w gives warnings'
	echo ' -r recurses through subdirectories'
	echo ' -h gives a help message and terminates'
	exit 1
    else
	if [ ""$1 = "" ] || [ ""$2 = "" ]; then 
	    echo "Too few arguments. Use -h for help."
	    exit 1
	fi
	SEARCH=$1

	if [ -e $DUMMY ]; then
	    echo "Aborting!!! Dummy file '"$DUMMY"' already exists!"
	    exit 1
	fi

	touch $DUMMY

	while ! [ ""$2 = "" ]; do
	    shift
	    if [ -d ""$1 ]; then 
		if [ ""$RECURSE = "-r" ]; then 
		    find $1 ! -type d -exec $0 $WARNING $SEARCH {} \;
		elif [ ""$WARNING = "-w" ]; then
		    echo "warning: "$1" is a directory. Try -r."
		fi
	    elif [ -f ""$1 ] && ! [ -x ""$1 ] && ! [ -h ""$1 ] ; then
		fgrep $SEARCH $DUMMY $1
	    elif [ ""$WARNING = "-w" ]; then
		if [ -h ""$1 ]; then
		    echo "warning: "$1" is a link. Skipping."
		elif [ -e ""$1 ]; then
		    echo "warning: "$1" is special. Skipping."
		elif [ -x ""$1 ]; then
		    echo "warning: "$1" is executable. Skipping."
		else
		    echo "warning: "$1" not found."
		fi
	    fi		
	done

	rm -f $DUMMY

	exit
    fi
done
