#!/bin/sh
#set -vx

PROG=`basename $0`
ESCFILE="./`basename $0`.tmp"

if [ "$#" -lt "2" -o "$#" -gt "3" ]; then
	printf "Usage: $PROG <regular expression> <file expression> [base path]\n"
	printf "Recursively runs vi on multiple files that match requested expressions.\n\n"
   printf "Note: You must use ticks around arguments that use globbing.\n\n"
	printf "Example: $PROG 'main(.+)' '*.cxx'\n"
	printf "Example: $PROG 'return retVal;' '*.h' /home/sella/sella_nms/src\n\n"
	printf "Report bugs to <sella@digital-genesis.com>.\n"
	exit 0
fi

if [ "$#" -eq "3" ]; then
	BASE="$3"
else
	BASE="."
fi
FILES=`find $BASE -name "$2"`
if [ "$?" -ne "0" ]; then
	exit 1
fi

for FILE in $FILES; do
	COUNT=`grep -cE "$1" $FILE`
	if [ "$?" -gt "1" ]; then
		exit 1
	fi
	if [ "$COUNT" -gt 0 ]; then
		NEWFILES="$NEWFILES $FILE"
	fi
done

ls $ESCFILE > /dev/null 2>&1
if [ "$?" -eq "0" ]; then
	printf "The escape file '%s' already exists. Someone trying something funny??\n" $ESCFILE
	exit 1;
else
	touch $ESCFILE
fi

for FILE in $NEWFILES; do
	LOC=`grep -nE "$1" $FILE | head -1 | sed 's/^\([0-9][0-9]*\):..*$/\1/'`
	printf "Modifying: %s:%d\n" $FILE $LOC
	vi +$LOC $FILE
	if [ "$?" -ne "0" ]; then
		exit 1
	fi
	ls $ESCFILE > /dev/null 2>&1
	if [ "$?" -ne "0" ]; then
		printf "Escape file was removed. Exiting early.\n"
		exit 1
	fi
done

rm $ESCFILE
