#! /bin/sh
##  A portable mail interface program.  Original by Piete Brooks,
##  modified by Rich $alz <rsalz@bbn.com>

mailer="${mailer-/usr/lib/sendmail}"
headers=false

##  Decode the arguments.
while test $# -gt 0 ; do
    arg="$1"
    shift
    case "$arg" in
    -A|-ASIS)
	asis=true
	;;
    -b|-body)
	body="$body
$1"
	shift
	;;
    -c|-cc)
	cc="$cc, $1"
	shift
	headers=true
	;;
    -f|-from)
	from="$1"
	shift
	headers=true
	;;
    -h|-help)
	cat <<EOF
Usage: $0 [flags] [recipients...]
	-A -ASIS	Send text ASIS, i.e. headers are present in the input
	-b -body	String which is to be the body of the message
	-c -cc		Carbon Copy recipients
	-f -from	From field
	-h -help	This message
	-r -recip	Recipient (passed on command line)
	-s -subject	Set the subject field
	-t -to		Main recipients
	-*		ERROR
	*		treat as recipients
EOF
	exit 1
	;;
    -r|-recip)
	recip="$recip $1"
	shift
	;;
    -s|-subject)
	subject="$subject, $1"
	shift
	headers=true
	;;
    -t|-to)
	to="$to, $1"
	shift
	headers=true
	;;
    -*)
	echo $0: invalid argument \""$arg"\"
	exit 1
	;;
    *)
	to="$to, $arg"
	;;
    esac
done

##  If no recipients, send to postmaster.
case "$to$cc$recip" in
'')
    recip=postmaster
    ;;
esac

##  If we got no headers on the command line, read them from the message.
case $headers in
false)
    asis=true
    ;;
esac

##  Strip off the spurious leading ", " in repeatable items
case "$to" in
', '*)
    to=`expr "$to" : ", \(.*\)`
    ;;
esac
case "$cc"  in
', '*)
    cc=`expr "$cc" : ", \(.*\)`
    ;;
esac
case "$subject"	in ', '*)
    subject=`expr "$subject" : ", \(.*\)`
    ;;
esac

##  Now do the business.
case "$mailer" in
*/sendmail|sendmail|*/sendmail' '*|sendmail' '*)
    args="-oi"
    if [ -z "$recip" ] ; then
	args="$args -t"
    fi
    (
	if [ ! -z "$subject" ] ; then
	    echo "Subject: $subject"
	fi
	if [ ! -z "$from" ] ; then
	    echo "From: $from"
	fi
	if [ ! -z "$to" ] ; then
	    echo "To: $to"
	fi
	if [ ! -z "$cc" ] ; then
	    echo "Cc: $cc"
	fi
	if [ -z "$asis" ] ; then
	    echo ""
	fi
	if [ -z "$body" ] ; then
	    cat
	else
	    echo "$body" | sed 1d
	fi
    ) | $debug $mailer $args $recip
    ;;

*/submit|submit|*/submit' '*|submit' '*)
    args="-tsz"
    case "$recip" in
    if [ -z "$recip" ] ; then
	if [ ! -z "$to" ] ; then
	    args="${args}gto*"
	fi
	if [ ! -z "$cc" ] ; then
	    args="${args}gcc*"
	fi
    fi
    (
	if [ ! -z "$subject" ] ; then
	    echo "Subject: $subject"
	fi
	if [ ! -z "$from" ] ; then
	    echo "From: $from"
	fi
	if [ ! -z "$to" ] ; then
	    echo "To: $to"
	fi
	if [ ! -z "$cc" ] ; then
	    echo "Cc: $cc"
	fi
	if [ -z "$asis" ] ; then
	    echo ""
	fi
	if [ -z "$body" ] ; then
	    cat
	else
	    echo "$body" | sed 1d
	fi
    ) | $debug $mailer $args $recip
    ;;

*)
    echo Unknown mailer 1>&2
    exit 1
    ;;

esac
