#!/bin/sh
#set -vx

PROG=`basename $0`

if [ "$#" -lt "2" -o "$#" -gt "3" ]; then
	printf "Usage: $PROG <sed expression> <file expression> [base path]\n"
	printf "Recursively runs sed over multiple files, altering the originals.\n\n"
   printf "Note: You must use ticks around arguments that use globbing.\n\n"
	printf "Example: $PROG 's/printf/vprintf/g' '*.cxx'\n"
	printf "Example: $PROG -e sedscript.txt '*.cxx' /home/sella/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

COUNT=0
for FILE in $FILES; do
	TMPFILE="/tmp/`basename $FILE`.$$"
	ls $TMPFILE > /dev/null 2>&1
	if [ "$?" -eq "0" ]; then
		printf "The tmpfile '%s' already exists. Someone trying something funny??\n" $TMPFILE
		exit 1;
	fi

	sed "$1" $FILE > $TMPFILE
	if [ "$?" -ne "0" ]; then
		exit 1
	fi
	diff --brief $TMPFILE $FILE > /dev/null
	DIFFRES=$?
	if [ "$DIFFRES" -gt "1" ]; then
		rm $TMPFILE
		exit 1
	elif [ "$DIFFRES" -eq 1 ]; then
		mv $TMPFILE $FILE
		printf "Modifed: %s\n" $FILE
	else
		rm $TMPFILE
	fi
	COUNT=`expr $COUNT + $DIFFRES`
done

printf "Files Modified: %d\n" $COUNT
