#!/bin/sh -

# vigrep - edit all files containing the given regexp
# Steve Kinzler, kinzler@cs.indiana.edu, Nov 93

set - $VIGREPOPTS ${1+"$@"}

grepout=; perl=; case=; bad=

while test $# -gt 0
do
	case "$1" in
	-e)	shift; EDITOR="$1";;
	-f)	shift; grepout="$1";;
	-g)	perl=;;
	-p)	perl=t;;
	-i)	case=i;;

	--)	shift; break;;
	-h|-\?)	bad=t; break;;
	-?*)	bad=t; echo "$0: unknown option ($1)" 1>&2;;
	*)	break;;
	esac
	shift
done

case "$bad" in
?*)	cat << EOF 1>&2; exit 1;;
usage: $0 [ -e editor ] [ -f file ] [ -g | -p ] [ -i ]
       [ regexp [ file ... ] ]
with no regexp, reads from the -f file else .grepout else ~/.grepout
with no files, greps on all files in the current directory
	-e	invokes the given editor or command head (default vi)
	-g	use grep regular expressions (default)
	-p	use perl regular expressions
	-i	use case-insensitive matching with the regexp
EOF
esac

case $# in
0)	case "$grepout" in
	'')	if   test -r .grepout;	     then grepout=.grepout
		elif test -r $HOME/.grepout; then grepout=$HOME/.grepout
		else echo "$0: cannot find .grepout" 1>&2; exit 2
		fi;;
	esac

	expr=`sed -n "2s/^[^']*'\([^']*\)'.*/\1/p; 2q" "$grepout"`

	set x `sed 's/:.*//; /[	 ]/d' "$grepout" | uniq`;;

*)	expr="$1"; shift

	case $# in
	0)	set - `ls -a | sed '/^\.$/d; /^\.\.$/d'`;;
	esac

	case $# in
	0)	set x;;
	*)	case "$perl" in
		?*)	set x `perl -ne 'print("$ARGV\n"),
					 close ARGV if '"/$expr/o$case" "$@"`;;
		*)	set x `grep -l"$case" "$expr" "$@"`;;
		esac;;
	esac;;
esac

shift
case $# in
0)	exit;;
esac

EDITOR=${EDITOR-vi}
case "$EDITOR" in
vi|view|vedit|ex|edit|e|more|less|\
*/vi|*/view|*/vedit|*/ex|*/edit|*/e|*/more|*/less)
	case "$expr" in
	?*)	EDITOR="$EDITOR '+/$expr'";;
	esac;;
'')	echo "$0: aborting, null editor" 1>&2; exit 3;;
esac

for arg
do
	args="$args '$arg'"
done

exec ${SHELL-sh} -c "$EDITOR $args"
