#!/bin/akanga -p
#


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

	return 0
	}


#
# pop3client [-d] <server> <username> <passwd>
#

debug = ''
if (~ $1 -d) {
	debug = yes;
	shift
	}
	
if (! ~ $#* 3) {
	echo usage: $0: '<server> <username> <passwd>' >[1=2]
	exit 1
	}

debug connecting to $1 ...
connect -p $1:110 akanga -c '
	fn readresp {
		if (! ~ $#* 0) {
			debug ''>>>'' $*
			echo $*
			}
			
		read flag line
		debug ''<<<'' $flag $line
		if (! ~ $flag +OK) {
			echo server responds: $flag $line >[1=2]
			exit 2
			}

#		echo $line
		return 0
		}

	debug 'connected.'
	STDOUT = /proc/self/fd/$CONNECT_STDIN

	readresp
	readresp USER $1
	readresp PASS $2

	readresp LIST
	bytes = 0
	while (read id octets line) {
		if (~ $id .) {
			break
			}

		msgid = ($msgid $id)
		let ''bytes = bytes + octets''
		}

	debug $#msgid messages, $bytes bytes on server ... >[1=2]

	for (i in $msgid) {
		file = $3 ^ . ^ $i
		readresp RETR $i
		{ while (read line  &&  ! ~ $line .) {
			echo $line
			}
		  } >$file

		echo $file >$STDOUT
		}

	readresp QUIT
	exit 0' $2 $3 mail

rc = $status
if (! ~ $rc 0) {
	echo 'status=' $rc
	}

exit $rc

