#! /bin/bash
B=/acminfo/5/hcibib/Work
LOG=$B/Info/hcibib.log

if test $# -ne 3
then
	echo Usage: ${0##*/} file filter target-dir
	exit 1
fi

file=$1
filter="$2"
dir=$3
okay=n
PGM=${0##*/}

function filter_copy # file filter dir log
	{
	cat $1 | $2 > $3/$1
	if test ! "$4" = ""
	then
		echo $PGM: updating $file
		echo "	$2 < $1 > $3/$1"
		# save log for anything ending in .bib
		if test "${1%.bib}" != "$1" -o "${1%.txt}" != "$1" -o "${1%.tmp}" != "$1"
		then
			/bin/ls -l $dir/$file | cut -c23- | sed "s@$dir/@@" >> $4
		fi
	fi
	}

# if file is newer than and differs from the target,
# then copy it over using the supplied filter

if test ! -r $dir/$file
then
	echo $PGM: no $dir/$file exists, so must copy
	filter_copy $file $filter $dir $LOG
elif test $file -nt $dir/$file
then
	cat $file | $filter | cmp -s - $dir/$file
	if test $? -ne 0
	then
		echo "$PGM: filtered file and target file differ"
		echo "	$filter $file"
		echo "	$dir/$file"
		okay=
		while test "$okay" = ""
		do
			echo -n "Okay to overwrite $dir/$file? [y(es n(o t(ouch d(iff]: "
			read okay
			if test "$okay" = "y" -o "$okay" = "Y"
			then
				filter_copy $file $filter $dir $LOG
			elif test "$okay" = "t"
			then
				touch -r $dir/$file $file
				echo "backdated mtime of $file to match target"
			elif test "$okay" = "d"
			then
				cat $file | $filter | diff - $dir/$file | ${VIEWER-more}
				okay=
			fi
		done
	fi
fi
