#!/bin/ash
# rustic `grep` (by M. Andreoli)
# using awk 

#set -x

usage()
{
cat <<END

(rustic AWK) grep, by M.Andreoli
Usage: grep [opts] pattern [files ...]
Options:
	-q	quiet
	-v 	invert

Please: separated options :-(

END
exit
}

# Syntax

[ $# -eq 0 ] && usage

quiet=0; invert=0
IGNORECASE=0

while [ $# != 0 ] ; do
case $1 in
-q)	quiet=1; shift;;
-v)	invert=1; shift ;;
-i)	IGNORECASE=1; shift;;
*)	break;;
esac
done

pattern=$1; shift; files="$@"

print_file=0
[ $# -gt 1 ] && print_file=1

exec mawk  -v pattern=$pattern -v invert=$invert -v IGNORECASE=$IGNORECASE \
      -v print_file=${print_file} -v quiet=$quiet \
-- '
BEGIN { 
rc=1
}
	{ 
	count= ($0 ~ pattern)
	if (invert) { count= !count;}
	if (! count) next; 
	rc=0
	if (quiet) next;
	if ( print_file )
		 print FILENAME ":" $0 
	else
		print $0; 
	}
END	{ exit(rc);}
' ${files}

