#!/bin/sh -
PATH=$PATH:/usr/local/lib:/usr/local/etc:/usr/lib:/etc:\
/usr/local/lib/news:/usr/lib/news; export PATH
umask 077

#ailagnt='sendmail -t -oi'
mailagnt='sentmail -t -oi'	# archives, fixes envelope
newsagnt='inews -h'

# sendfile - submit the given files to backgrounded, nohuped delivery agents
# Steve Kinzler, steve@kinzler.com, Feb 94
# https://kinzler.com/me/home.html#unix

agent="$mailagnt"; prompt=t; verbose=; delay=; inopts=; opts=; bad=

while :
do
	case $# in
	0)	break;;
	*)	case "$inopts" in
		?*)	case "$1" in
			--)	inopts=;;
			*)	opts="$opts '$1'";;
			esac;;

		*)	case "$1" in
			-m)	agent="$mailagnt";;
			-n)	agent="$newsagnt";;
			-p)	prompt=t;;
			-f)	prompt=;;
			-v)	verbose=t;;
			-d)	shift; delay="$1";;
			--)	inopts=t;;

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

case "$delay" in
''|[0-9]*)	;;
*)		bad=t; echo "$0: invalid seconds ($delay)" 1>&2;;
esac

case "$bad" in
?*)	cat << EOF 1>&2
usage: $0 [ -m | -n ] [ -p | -f ] [ -v ] [ -d seconds ]
       [ -- delivery agent options -- ] [ file ... ]
	-m	send mail message with "$mailagnt" (default)
	-n	send news article with "$newsagnt"
	-p	prompt before sending each file (default)
	-f	force sending files without prompting
	-v	report files as they're sent
	-d	delay seconds between each sending
EOF
	exit 1;;
esac

case $# in
0)	set x -; shift;;
esac

agent="$agent$opts"
pid=$$

for file
do
	case "$file" in
	"$1")	;;
	*)	case "$delay" in
		?*)	case "$prompt$verbose" in
			?*)	echo "sleeping $delay seconds ...";;
			esac
			sleep "$delay";;
		esac;;
	esac

	name=$file
	case "$file" in
	-)	case "$tmp" in
		'')	tmp=/tmp/sf$$
			if cat > $tmp
			then
				:
			else
				tmp=
				continue
			fi;;
		esac
		file=$tmp;;
	esac

	case "$prompt" in
	?*)	sed '/^$/q' < $file || continue
		echo "$agent < $name? [y] " | tr -d '\012'
		# this has been observed to behave badly under Linux
		# ie, a single <Return> answered multiple "read"s
		read answer < /dev/tty
		case "$answer" in
		''|[yY]*)	;;
		*)		continue;;
		esac;;
	esac

	pid=`expr $pid + 1`
	tmpF=/tmp/sfF$pid
	tmpS=/tmp/sfS$pid

	if echo "(cat $tmpF; rm -f $tmpF $tmpS) | $agent" > $tmpS &&
	   cat "$file" > $tmpF
	then
		case "$verbose" in
		?*)	echo "sending $file to '$agent'";;
		esac
		(trap '' 1 15; exec sh $tmpS) &
	else
		rm -f $tmpF $tmpS
	fi
done

rm -f $tmp
