#!/usr/athena/bin/perl -w
#
# $Id: check.pl,v 1.2 2004/05/31 01:51:30 jhawk Exp jhawk $
#
# Check/retrieve imap mail.

# use strict;
use Cyrus::IMAP;


sub fetch_callback(@);


sub fetch_callback(@) {
    my %cb = @_;
    print "In FETCH callback: msgno $cb{-msgno} text $cb{-text}\n";
    $_ = $cb{-text};
    # Extract the body size, and strip off the response up to the body.
    my $size = $1 if s/.*?BODY\[\] \{(\d+)\}\r\n//ios;
    return unless $size;
    # Extract the body text.
    $_ = substr($_, 0, $size);
    # Convert to Unix-style EOL.
    s/\r\n/\n/gos;
    print $_;
}



$ENV{"KRBTKFILE"}="/tmp/tkt_imapmon_$$";
$ENV{"KRB5CCNAME"}="/tmp/krb5cc_imapmon_$$";
$ENV{"promptkt"}=":sipb2";	# jhawkdotfiles

# Get krb5 tickets
system("kinit -k -t auth/sipb2.kt sipb2");

# Interactive tests
# system("/bin/athena/tcsh");

$username="sipb2";
$host="po11.mit.edu";

my ($status, $text);
my $client = Cyrus::IMAP->new($host) ||
    die "Cannot connect to IMAP server on $host";

$client->addcallback({-trigger => 'FETCH', -flags => Cyrus::IMAP::CALLBACK_NUMBERED,
                      -callback => \&fetch_callback});


$client->authenticate(-authz => $username) ||
    die "Cannot authenticate to $host";
($status, $text) = $client->send('', '', "SELECT INBOX");
print "Response: status $status, text <$text>\n";
($status, $text) = $client->send('', '', "FETCH 1 RFC822");
print "Response: status $status, text <$text>\n";

($status, $text) = $client->send('', '', "LOGOUT");
print "Response: status $status, text <$text>\n";
$client->DESTROY();



# $pid = open2(*Reader, *Writer, "athrun imap imtest -k po11 143");
# $pid = open2(*Reader, *Writer, "imtest po11");
# print "pid $pid\n";
# while (<Reader>) {
#     print "<$_>";
#     last if $_ eq "Authenticated.\n";
# }
# print Writer "A SELECT INBOX\n";
# print Writer "A FETCH 1 RFC822\n";
# print Writer "A LOGOUT\n";
# while (<Reader>) {
#     print $_;
# }
# print "postwrite\n";
# while (<Reader>) {
#     print $_;
# }
# print <Reader>;
# print <Reader>;

# Punt krb5 tickets
system("kdestroy");
