#!/bin/sh
# batchcsmtp
# (Brian Candler; based on smail/samples/bsmtp/cbsmtp.sh)  14 Oct 94

# deliver messages accumlated into subdirectories of the
# outq spool directory.  Subdirectory names are based on
# the actual hostnames involved.

# Note from Brian:
# This version takes the host name(s) from the command line, rather than
# looping through all subdirectories; e.g. "batchcsmtp ucb isis". Changed
# compression to use gzip, and added "|| exit 1" to end of uux so that
# mail files don't get deleted if uux fails.
# Added feature: messages over a certain size are truncated. This is
# intended to prevent huge phone charges from megabyte files being sent.
# (Smail is supposed to have this feature, but it doesn't work yet!)

LOCALHOST=`hostname`      # put hostname here if different
MAXSIZE=450000            # or around 150K after compression, hopefully

THRESHOLD=210000          # truncate messages which are larger than this...
TRUNCSIZE=10000           # ...down to this size (there's no point keeping
                          # lots if you're going to break it anyway)

OUTQ=/var/spool/smail/outq
UUX="/usr/bin/uux - -r -z"
COMPRESS="/bin/gzip -c -9"    # CHECK the location of this!

cd $OUTQ || exit 1

# loop through all of the subdirectories specified
for host in "$@"
do
    (
	# change to directory or exit subshell
	test -d $host || exit 1
	cd $host || exit 1

	# send multiple batches
	while :
	do
		# get the list of message files; quit if none
		msgs="`ls 2>/dev/null | grep '^q'`"
		test -n "$msgs" || break

		# accumulate until total size exceeds maximum
		send=
		sz=0
		for f in $msgs
		do
			send="$send $f"
			n=`wc -c <$f 2>/dev/null`
			test -n "$n" || continue
			test $n -lt $THRESHOLD || {
				{
				head -c $TRUNCSIZE $f
				echo ""
				echo "** --------------------"
				echo "** Warning from MAILER-DAEMON@$LOCALHOST:"
				echo "** This message, originally $n bytes, was larger than the limit of"
				echo "** $THRESHOLD bytes and hence was truncated. Only the first $TRUNCSIZE bytes"
				echo "** were retained. This is to prevent accidental large E-mail bills."
				echo "** If you are sure you wish to receive this large file, you will need"
				echo "** to have it broken into smaller chunks which are mailed separately."
				echo "** --------------------"
				echo "."   # recreate SMTP end-of-message
				} > $f.t
				mv -f $f.t $f
				n=$TRUNCSIZE
				# roughly!
			}
			sz=`expr $sz + $n`
			test $sz -lt $MAXSIZE || break
		done

		# send compressed messages, adding HELO and QUIT commands
		( echo "HELO $LOCALHOST"
		  for f in $send
		  do
			  cat $f
		  done
		  echo QUIT ) |
		$COMPRESS | $UUX $host!rcsmtp || exit 1

		# remove messages that were sent
		for f in $send
		do
			rm $f
		done
	done
    )
done

exit 0
