#! /bin/sh
:
#ident	"@(#)contrib:RELEASE-3_2_0_115:bouncemail.sh,v 1.7 2003/01/16 19:33:56 woods Exp"
#
#	bouncemail.sh - bounce a mail message after one more try
#
# Written by Greg A. Woods while at Nirv Centre / Web Networks <woods@web.net>
# Contributed to the public domain.
#

umask 022

TMPDIR="/var/mail/tmp"
if [ ! -d $TMPDIR ] ; then
	if ! mkdir $TMPDIR ; then
		echo "$0: $TMPDIR exists as a file!" 1>&2
		exit 1
	else
		chmod 700 $TMPDIR
	fi
fi

SMAIL_NAME="/usr/sbin/smail"

TMPFILES="$TMPDIR/tc$$ $TMPDIR/et$$ $TMPDIR/qu$$"
trap 'rc=$?; rm -f $TMPFILES; exit $rc' 0 1 2 3 13 15

argv0=`basename $0`

USAGE="Usage: $argv0 [-v[N]] message_queue_id [...]"

case "$1" in
-v*)
	verbose="$1"
	shift
	;;
-*)
	echo $USAGE 1>&2
	exit 2
	;;
esac

if [ $# -lt 1 ] ; then
	echo $USAGE 1>&2
	exit 2
fi

if expr "`id`" : '^uid=0(root)' >/dev/null ; then
	:
else
	echo "$argv0:  ERROR:  you must be root to do this!" 1>&2
	exit 1
fi

# XXX this "echo" determination is cut&paste from my .profile <woods@planix.com>
HAVEPRINT=false ; export HAVEPRINT
if expr "`type print`" : '^print is a shell builtin$' >/dev/null 2>&1 ; then
	HAVEPRINT=true
fi
HAVEPRINTF=false ; export HAVEPRINTF
if expr "`type printf`" : '^printf is a shell builtin$' >/dev/null 2>&1 ; then
	HAVEPRINTF=true
elif expr "`type printf`" : '.* is .*/printf$' >/dev/null 2>&1 ; then
	HAVEPRINTF=true
fi
# always use ``$echo'' if any of the other variables are used...
#	$nl - print a newline (always required at end of line if desired)
#	$n - option to turn off final newline
#	$c - escape sequence to turn off final newline
# usage for a prompt is:
#	$echo $n "prompt: $c"
# and for a normal line
#	$echo "message$nl"
#
if $HAVEPRINT ; then
	# use ``$echo'' if any of the other variables...
	echo=print
	nl='\n'
	n='-n'
	# XXX in theory '\c' is equivalent of '-n' in most shells
	c=''
elif $HAVEPRINTF ; then
	# use ``$echo'' if any of the other variables...
	echo=printf
	nl='\n'
	n=''
	c=''
else
	(echo "hi there\c" ; echo " ") >$TMPDIR/et$$
	echo=echo
	#
	# lwall's Configure test of the same nature also checks to
	# make sure grep returns a status...
	# 
	if grep c $TMPDIR/et$$ >/dev/null 2>&1 ; then
		nl=''
		n='-n'
		c=''
	else
		nl='\n'
		n=''
		c='\c'
	fi
	rm -f $TMPDIR/et$$
fi

$SMAIL_NAME -bp ${1+"$@"} > $TMPDIR/qu$$
if [ ! -s $TMPDIR/qu$$ ] ; then
	echo "$argv0: no message matching '${1+"$@"}'" 1>&2
	exit 1
fi

echo "One more delivery attempt will be made and then"
echo "the following message(s) will be bounced back to the sender:"
cat $TMPDIR/qu$$
$echo $n "Do you want to continue? [n] $c"

read ans junk
case "$ans" in
y*|Y*)
	;;
*)
	echo "$argv0: Aborting..." 1>&2
	exit 1
	;;
esac

echo "* 0/0" > $TMPDIR/tr$$

$SMAIL_NAME $verbose -oE $TMPDIR/tr$$ -q ${1+"$@"}

exit $?
