#!/bin/akanga -p
#


fn debug {
	if (~ $debug yes) {
		echo $* >[1=2]
		}

	return 0
	}


#
# readresponse <expect> <exitcode>
#
fn readresponse {
	while (read line) {
		debug '<<<' $line
		if (! ~ $line [0-9][0-9][0-9]-) {
			smtpcode = `{ echo $line }
			smtpcode = $smtpcode(1)
			break
			}
		}

	if (! ~ $smtpcode $1) {
		echo smtpsend: SMTP error: got " ^ $line ^ ", expected $1 >[1=2]

		if (~ $#* 2  &&  ! ~ $2 0) {
			echo QUIT
			exit $2
			}

		return 1
		}
	
	return 0
	}

#
# putline <line>
#
fn putline {
	if (~ $debug yes)
		echo '>>>' $* >[1=2]

	echo $*
	return 0
	}

#
# smtpcommand <expect> <exitcode> <cmd> ...
#
fn smtpcommand {
	expect = '' exitcode = '' {
		expect = $1; exitcode = $2; shift 2
		putline $*
		readresponse $expect $exitcode
		}
		
	return 0
	}

#
# senddata
#
fn senddata {
	awk '{ if ($0 == ".") $0 = "." $0; print $0; }' $*
	return 0
	}


#
# smtpsend [<options>] <server> <sender> <rcpt> ...
#
#
#   exitcodes:
#
#	1 - can't connect to server
#	2 - error in server greeting
#	3 - HELO error
#	4 - MAIL FROM error
#	5 - no valid recipients
#	6 - error after DATA or after message
#

initvars '' debug subject opt_reportsuccess opt_reporterror opt_reportany
parseopt '*' aders:v $*  ||  exit 1

while (~ $1 -*) {
	switch ($1) {
	case -a
		opt_reportany = yes
		shift

	case -d -v
		debug = yes
		shift
	
	case -e
		opt_reporterror = yes
		shift

	case -r
		opt_reportsuccess = yes
		shift

	case -s
		subject = $2
		shift 2

	case - --
		shift
		break

	case *
		echo $0: unkown option: $1 >[1=2]
		exit 1
		}
	}


if (~ $#* 0 1 2) {
	echo usage: $0: '<server> <sender> <rcpt>' >[1=2]
	exit 1
	}


server = $1; sender = $2; shift 2
if (~ $sender '')
	sender = `{ whoami }

rcptlist = $*
rcpts = ()

debug connecting to server ...
connect -p $server:25 akanga -c '
	stdout = /proc/self/fd/$CONNECT_STDOUT
	stdin = /proc/self/fd/$CONNECT_STDIN
	
	readresponse 220 2
	smtpcommand 250 3 HELO `{ cat /etc/HOSTNAME }
	smtpcommand 250 4 ''MAIL FROM:<'' ^ $sender ^ ''>''

	for (rcpt in $rcptlist) {
		smtpcommand 250 0 ''RCPT TO:<'' ^ $rcpt ^ ''>''
		if (~ $opt_reportany yes) {
			echo $smtpcode $rcpt >$stdout
		} else if (~ $opt_reportsuccess yes  &&  ~ $smtpcode 250) {
			echo $smtpcode $rcpt >$stdout
		} else if (~ $opt_reporterror yes  &&  ! ~ $smtpcode 250) {
			echo $smtpcode $rcpt >$stdout
			}

		~ $smtpcode 250  &&  rcpts = ($rcpts $rcpt)
		}

	if (~ $#rcpt 0) {
		echo $0: no valid recipients >[1=2]
		exit 5
		}
		
	smtpcommand 354 6 DATA

	if (! ~ $subject '''') {
		echo Subject: $subject
		echo
		}
		
	senddata $stdin
	smtpcommand 250 6 .
	smtpcommand 221 0 QUIT
	'  ||  exit $status

exit 0

