#!/afs/athena/contrib/perl/perl

package popmail;

require "chat2.pl";

$ENV{'MAILHOST'} = "dt";
$pop_timeout = 10;

sub lose {
	local ($err) = @_;
	printf STDERR "error %d\n", $err;
	if ($err == -1) {
		printf STDERR "POP error message: %s\n", $pop_err_msg;
	}
	&chat'print ("quit\n");	
	exit (1);
}
 
sub expect_ok {
	local $ok_msg;
	local ($result) = &chat'expect ($pop_timeout,
		'^\+OK(.*)\r\n', 	'$ok_msg = $1; 0',
		'^\-ERR((.|\n)*)\r\n', 	'$pop_err_msg = $1; -1',
		'TIMEOUT', 		'-2',
		'EOF', 			'-3'
	);	
	if ($result < 0) {
		do lose ($result);
	}
	if ($result < 0)
	return $ok_msg;
}

sub expect_multi_line {
	&expect_ok ();
	local @textlines;
	
	$result = 1;
	while ($result) {
		$result = &chat'expect ($pop_timeout,
			'^\.\r\n',		0,
			'^(.*)\r\n',		'push (@textlines, $1); 1',
			'TIMEOUT', 		-2,
			'EOF', 			-3);

		if ($result < 0) {
			$result = &lose ($result);
		}
	}	
	return @textlines;
}

# The cmd_user and cmd_pass routines are used in the AUTHORIZATION state
# of the POP 3 session.

sub cmd_user {
	local ($user) = @_;
	$user = $user || $ENV{'USER'};
	do chat'print ("USER $user\n");
	do expect_ok ();
}

sub cmd_pass {
	local ($pass) = @_;
	$pass = $pass || $ENV{'USER'};  # With Kerberos, pass username,
					# which is a dummy anyway.
	do chat'print ("PASS $pass\n");
	do expect_ok ();
}

# The cmd_retr routine retrieves the whole text of the message, header
# and body, as an array of lines.

sub cmd_retr {
	local ($msg_number) = @_;
	do chat'print ("RETR $msg_number\n");
	local (@msg_lines) = &expect_multi_line ();
	return @msg_lines;
}

sub cmd_list {
	local ($msg_number) = @_;
	local ($msg_id, $msg_size);
	&chat'print ("LIST $msg_number\n");
	if ($msg_number) {
		&expect_ok () =~ /(\d+)\s+(\d+)/;
		($msg_id, $msg_size) = ($1, $2);
	}
	else {
		
	}
}

sub cmd_quit {
	&chat'print ("QUIT\n");
}

sub cmd_dele {
	local ($msg_number) = @_;
	&chat'print ("DELE $msg_number\n");
	&expect_ok ();
}

sub cmd_top {
	local ($msg_number, $lines_of_body) = @_;
	&chat'print ("TOP $msg_number $lines_of_body\n");
	&expect_multi_line ();
}

sub cmd_reset {
	&chat'print ("RSET\n");
	&expect_ok ();
}

$handle = &chat'open_proc ("kpoptcp");

&expect_ok ();

&chat'print ("user $ENV{'USER'}\n");

&expect_ok ();

&chat'print ("pass $ENV{'USER'}\n");

&expect_ok ();

&chat'print ("list\n");

@lines = &expect_multi_line ();

print "list output:\n";

print join ("\n", @lines), "\n";
 
&chat'print ("retr 1\n");

@lines = &expect_multi_line ();

print "retr output:\n";

print join ("\n", @lines), "\n";

&chat'print ("quit\n");



