#!/bin/sh -

# tmpto - place or append input into the given files all at once
# Steve Kinzler, steve@kinzler.com, Oct 18/Aug 24/Oct 24
# https://kinzler.com/me/home.html#unix

append=; nonzero=

while :
do
	case $# in
	0)	break;;
	*)	case "$1" in
		-a)	append=$1;;
		-z)	nonzero=$1;;

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

case "$bad" in
?*)	cat << EOF 1>&2
usage: $0 [ -a ] [ -z ] [ file ... ]
	-a	append the input to the files
	-z	do nothing if the input is empty
EOF
	exit 1;;
esac

tmp="${TMPDIR:-/tmp}/tmpto$$"
trap "rm -f '$tmp'; exit" 0 1 2 13 15
cat > "$tmp" || exit 2

test -n "$nonzero" -a \! -s "$tmp" && exit 0

for file
do
	case "$append" in
	?*)	cat < "$tmp" >> "$file";;
	*)	cp "$tmp" "$file";;
	esac
done
