#!/usr/bin/perl
# Simple mail client

die "Usage: pop3.pl <servername>\n" unless @ARGV == 1;

use Net::POP3;
$MailAgent = Net::POP3->new($ARGV[0]) or die "Could not open account: $!\n";

# Login to the POP3 server
# Save the # of messages to $num_msgs
# Save the messages in $messages
system("clear");
print "Username: ";
chomp($username = <STDIN>);
print "Password: ";
chomp($password = <STDIN>);
$num_msgs = $MailAgent->login($username, $password);
$messages = $MailAgent->list();

while (1) {
	# Present Menu
	system("clear");
	print "1) See number of new messages\n";
	print "2) Preview message headers\n";
	print "3) Delete a message\n";
	print "4) Download a message\n";
	print "5) Download all messages\n";
	print "6) Save messages\n";
	print "7) Quit\n";
	print "\nChoice: ";
	
	chomp($action = <STDIN>);
	
	$action == 1 && number_msgs();
	$action == 2 && preview_msg();
	$action == 3 && delete_msg();
	$action == 4 && download_msg();
	$action == 5 && download_all_msgs();
	$action == 6 && save_msgs();
	$action == 7 && quit();
}

sub number_msgs {
	print "Number of new messages: $num_msgs\n";
	print "Press ENTER to continue\n";
	<STDIN>;
}

sub preview_msg {
	print "Preview which message? ";
	chomp($msgnum = <STDIN>);
	print "Message $msgnum (", $messages->{$msgnum}, "):\n";
	$this_message = $MailAgent->top($msgnum, 3);
	print @$this_message, "\n";
	print "Press ENTER to continue\n";
	<STDIN>;
}

sub delete_msg {
	print "Delete which message? ";
	chomp($msgnum = <STDIN>);
	$MailAgent->delete($msgnum);
	print "Message $msgnum (", $messages->{$msgnum}, ") deleted\n";
	print "Press ENTER to continue\n";
	<STDIN>;
}

sub download_msg {
	print "Download which message? ";
	chomp($msgnum = <STDIN>);
	$this_message = $MailAgent->get($msgnum);
	print "Message $msgnum (", $messages->{$msgnum}, ") downloaded\n";
	push(@downloaded_messages, $this_message);
	push(@downloads, $msgnum);
	print "Press ENTER to continue\n";
	<STDIN>;
}

sub download_all_msgs {
	@downloaded_messages = ();
	foreach $msgnum (keys %$messages) {
		$this_message = $MailAgent->get($msgnum);
		print "Message $msgnum (", $messages->{$msgnum}, ") downloaded\n";
		push(@downloaded_messages, $this_message);
		push(@downloads, $msgnum);
	}
	print "Press ENTER to continue\n";
	<STDIN>;
}

sub save_msgs {
	print "Currently downloaded messages: \n[ ";
	foreach $msgnum (@downloads) { print "$msgnum "; }
	print "]\n";
	print "Save these messages?[y/n] ";
	chomp($save = <STDIN>);
	if ($save =~ /y/i) {
		print "Save location: ";
		chomp($save_path = <STDIN>);
		open(FOUT, ">$save_path");
		foreach $this_message (@downloaded_messages) {
			$this_message = join('', @$this_message);
			print FOUT $this_message, '=' x 60, "\n";
		}
		close(FOUT);
		print "Messages saved\n";
	} else {
		print "No messages saved\n";
	}
	print "Press ENTER to continue\n";
	<STDIN>;
}

sub quit {
	$MailAgent->quit();
	exit(0);
}
