#!/bin/bash

## mini-expect {{{ 
EXPECT_IN=0
EXPECT_OUT=1

spawn() {
	coproc "$@"
	EXPECT_IN=${COPROC[0]}
	EXPECT_OUT=${COPROC[1]}
}

expect() {
	local expect_str="$1"
	while read -r line <&${EXPECT_IN} ; do
		echo "$line"
		if [[ $line =~ $expect_str ]] ; then
			return
		fi
	done
}

send() {
	echo -n "$@"
	echo -n "$@" >&${EXPECT_OUT}
}
## }}}

## test-script {{{

spawn nc localhost 25

expect "220 test-mail-server.example.com ESMTP phplibsmtpd"

send $'EHLO client-hostname.example.com\r\n'

expect "250"

send $'MAIL FROM:<bob@example.org>\r\n'

expect "250"

send $'RCPT TO:<alice@example.com>\r\n'

expect "250"

send $'RCPT TO:<theboss@example.com>\r\n'

expect "250"

send $'DATA\r\n'

expect "354"

send $'From: "Bob Example" <bob@example.org>\r\n'
send $'To: "Alice Example" <alice@example.com>\r\n'
send $'Cc: theboss@example.com\r\n'
send $'Date: Tue, 15 January 2008 16:02:43 -0500\r\n'
send $'Subject: Test message\r\n'
send $'\r\n'
send $'Hello Alice.\r\n'
send $'This is a test message with 5 header fields and 4 lines in the message body.\r\n'
send $'Your friend,\r\n'
send $'Bob\r\n'
send $'.\r\n'

expect "250"

send $'QUIT\r\n'

## }}}
