#!/usr/bin/perl
use Socket;

# ******************************************************
# A simple perl script to check the remote mailbox!
# Not biff but something like biff!
# ******************************************************

# How often do you want to check the remote mailbox?(in seconds) 
# Here default is 30 seconds!(xbiff default!)
$repeat_time = 30;

# User name at the pop server.
$user = "jchakma";

# pop server: IP address or hostname
$popserver = "192.168.1.1";

# getting the password by turning the echo off
system "stty -echo";
print "Enter password for jchakma\@$popserver: ";
chop($password = <STDIN>);
print "\n";
system "stty echo";

while (1 == 1) # an infinite loop! Be carefule!
{
    # Ok, let's open the connection
    $proto = getprotobyname('tcp');
    socket(SERVER, AF_INET, SOCK_STREAM, $proto);
    $iaddr = gethostbyname($popserver);
    $port = getservbyname('pop-3', 'tcp');
    $sin = sockaddr_in($port, $iaddr);
    connect(SERVER, $sin) || die "Connection failed to $popserver\n";
    recv SERVER, $reply, 512, 0; # The first greeting!

    # Trying to log in! Passing the username!
    send SERVER, "USER $user\r\n", 0;
    recv SERVER, $reply, 512, 0;

    # Trying to log in! Passing the password 
    # Be careful, it's plain text password!
    send SERVER, "PASS $password\r\n", 0;
    recv SERVER, $reply, 512, 0;

    # Checking the reply! If it's +OK, then
    # the login was successful, otherwise die
    $reply =~ /^\+OK/ || die "Login failed to $popserver\n";
    print "Logged in\n";

    send SERVER, "STAT\r\n", 0;
    recv SERVER, $reply, 512, 0;

    # Testing how many messages are there!
    if ($reply =~ /^\+OK/)   # Got a OK STAT reply
    {
       chop $reply;
       ($status, $message, $len) = split (/\s+/, $reply);
       if ($message > 0)
       {
           print "You got: $message messages (total length: $len octets)\n";
           send SERVER, "TOP 1 5\r\n", 0;
           print "Top message goes like this:\n";

	   # let's pring the message header and few lines!
           while ($line = <SERVER>)
           {
               chop $line;
	       if ($line =~ /^\./)  # this indicates end of message!
	       {
	          last;
	       }
	       print "$line\n";
           }
       }
       else
       {
           print "Sorry no message\n";
       }
    }

    # Bye! bye!
    send SERVER, "RSET\r\n", 0;
    recv SERVER, $reply, 512, 0;
    send SERVER, "QUIT\r\n", 0;
    recv SERVER, $reply, 512, 0;
    #print "$reply\n";

    close SERVER;
 
    # Sleep before trying for another time!
    sleep $repeat_time; 
}
