#! /usr/bin/perl -w
# $Id: imcheck,v 1.2 2002/07/02 18:25:18 kaj Exp $
use strict;
use Getopt::Std;
use lib '/home/e91/kaj/src/imaputil';
use ImtestImap;

my ($host, $limit) = ('imap', 10);

my %opts;
getopts('zhs:l:r', \%opts);
if(defined $opts{h}) {
    print "Usage: $0 -z -h folders\n\n"
	. "\t-h\tGives this helpfull message\n"
	. "\t-l num\tShow only num messages per folder (default is $limit)\n"
	. "\t-s host\tUse host as the imap server (default is '$host')\n"
	. "\t-z\tGives \"zephyr markup\" in the output.\n"
	. "\nSample:\n\t$0 INBOX INBOX.foo lists.freebsd.ports\n";
    exit 0;
}

my ($start_h, $end_h) = 
    (defined $opts{z}
     ? ('@font(-*-helvetica-bold-o-*-*-18-*)', '@font(courier)')
     : ('', ''));
$host  = $opts{s} if defined $opts{s};
$limit = $opts{l} if defined $opts{l};
my $realnames = defined $opts{r};

my $imap = new ImtestImap($host);
$imap->cmd('NOOP');

@ARGV = ('INBOX') if($#ARGV == -1);

foreach my $folder (@ARGV) {
    my @rows; 
    $imap->cmd("EXAMINE $folder", \@rows);
    my ($unseen, $exists);
    foreach(@rows) {
#	print "::: $_";
	$unseen = $1 if /UNSEEN ([0-9]+)/;
	$exists = $1 if /([0-9]+) EXISTS/;
    }
    
    if(defined $unseen && defined $exists) {
	print "$start_h$folder$end_h\n" unless ($#ARGV == 0);
	if($exists - $unseen > $limit) {
	    print "To many (potential) unseen messages, limiting to $limit.\n";
	    $unseen = $exists - ($limit -1);
	}
	my @rows;
	$imap->cmd("FETCH $unseen:$exists"
		   . ' (FLAGS BODY[HEADER.FIELDS (FROM SUBJECT)])',
		   \@rows);
	my ($subject, $from, $flags) = ('', '', '');
	foreach(@rows) {
	    chop; chop;
#	    print ">>>$_\n";
	    if(/\* ([0-9]+) FETCH \(FLAGS \(([^\)]*)\)/) {
#		print "... Msg ...\n";
		$flags = $2;
		$subject = '';
		$from = '';
	    } elsif(/^Subject: (.*)$/) {
		$subject = $1;
	    } elsif(/^From: (.*)$/) {
		$from = $1;
	    } elsif(/^\)$/) {
#		print ">>>$from\t$subject\n";
#		print "Flags: $flags\n";
		if($realnames
		   && $from =~ /^([^<]+[^ <])/) {
		    $from = $1;
		}
		print unquote("$from\t$subject\n") unless $flags =~ /Seen/;
	    }
	}
	print "\n" unless ($#ARGV == 0);
    } else {
	print "No unseen mail in $folder\n\n"
    }
}

sub unquotesub {
    my ($line, $metod, $encoding) = @_;
    if ($metod =~ /[Qq]/ && $encoding =~ /^[Ii][Ss][Oo][-_]?8859[-_]1$/) {
	$line =~ s/=([0-9A-Fa-f]{2})/pack('H2', $1)/eg;
	$line =~ s/_/ /g;
	return $line;
    } elsif ($metod =~ /[Bb]/) {
#	$line = decode_base64($line);
    }
    return "=?$encoding?$metod?$line?=";
}

sub unquote {
    my ($l) = @_;
    $l =~ s/=\?([^\?]*)\?(q|Q|B|b)\?([^\?]*)\?=/unquotesub($3, $2, $1)/ge;
    $l;
}
