#!/bin/sh
#
#	overwrite: copy standard output generated from another command
#	to the specified file after EOF
#
#	Refer to "The Unix Programming Environment", pp. 154

case $# in
0) echo "overwrite -- copy the standard output generated from another command"
	echo "to the specified file after EOF."
	echo
	echo "Usage 1:"
	echo "  overwrite file command arguments"
	echo
	echo "Usage 2:"
	echo "  command argments | overwrite file"
	echo
	echo "command arguments:"
	echo "  could by anything, e.g., grep abc file"
	echo "file:"
	echo "  could be the same as the file processed the command"
	echo
	echo "In Usage 1, file won't be changed if command doesn't succeed."
	exit 0;;
esac

file=$1; shift
flbase=${file##*/}
new=/tmp/$flbase.overwrite1~
old=/tmp/$flbase.overwrite2~

trap 'rm -f $new $old; exit 1' 1 2 15	#clean up upon signals

if [ $# -ge 1 ] ; then
	$* > $new
	if [ $? != 0 ] ; then
		echo "overwrite: $1 failed, $file unchanged" 1>&2
		rm -f $new $old
		trap - 1 2 15
		exit 1
	fi
else
	cat > $new
fi

#if [ -f $file ] ; then
#	cp -f $file $old	#useful if 'cp $new $file' fail
#fi

trap '' 1 2 15	#ignore signals
cp -f $new $file	#overwire (not mv) to preserve permissions
rm -f $new $old
trap - 1 2 15	#restore
