#!/bin/ash
#################################
# mu-grep : rustic grep 
# [ only ash commands ]
#(by M. Andreoli)
#################################
 
#set -x

# Syntax


[ $# = 0 ] && echo "Usage (mu-grep): grep [-v] string [files]" && exit;

# Start

opt=$1

case "$opt" in
-v) shift;;
*) opt=
esac
	

what=$1;
shift 1
where=$*

ok=1

for f in ${where} 
do
	cat "$f" | while read line
	do

	case $line in
	*$what*) 
		if [ "${opt}" != "-v" ] ; then
		echo "$f:$line"
		ok=0	
		fi
		;;
	*)
		if [ "${opt}" = "-v" ] ; then
                echo "$f:$line"
		ok=0
                fi
		;;	
	esac
	done
done

# stdin

if [ -z "${where}" ] ; then
        while read line
        do
	        case $line in
        *$what*)
                if [ "${opt}" != "-v" ] ; then
                echo "$line"
		ok=0
                fi
                ;;
        *)
                if [ "${opt}" = "-v" ] ; then
                echo "$line"
		ok=0
                fi
                ;;
        esac

        done
fi


return $ok

# End
