#! /usr/bin/perl -w
# $Id: imlsfolders,v 1.3 2002/07/02 19:32:50 kaj Exp $
use strict;
use Getopt::Std;
use lib "/home/e91/kaj/src/imaputil";
use ImtestImap;

my ($host, $lcmd, $base) = ('imap', 'LSUB', '');

my %opts;
getopts('b:hs:uq', \%opts);
if(defined $opts{h}) {
    print "Usage: $0 [options]\nWhere options may include:\n\n"
	. "\t-b base\tOnly include subfolders of base (included)\n"
	. "\t-h\tGives this helpfull message\n"
	. "\t-s host\tUse host as the imap server (default is '$host')\n"
	. "\t-u\tInclude unsubscribed folders in the listing\n"
	. "\t-q\t(quiet) Supress heading\n";
    exit 0;
}

$base = $opts{b} if defined $opts{b};
$host = $opts{s} if defined $opts{s};
$lcmd = 'LIST'   if defined $opts{u};

print "UNREAD\tTOTAL\tFOLDER\n" unless defined $opts{q};

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

my @rows;
my $result = $imap->cmd("$lcmd \"$base\" *", \@rows);
foreach (@rows) {
    if(/$lcmd .* \"([^\"]*)\"/) {
	my $box = $1;
	my @row;
	$result = $imap->cmd("STATUS $box (MESSAGES UNSEEN)", \@row);
	foreach(@row) {
	    if(/STATUS $box \(MESSAGES ([0-9]+) UNSEEN ([0-9]+)\)/) {
		print "$2\t$1\t$box\n";
#		print "($2)" if($2 > 0);
#		print "\n";
	    } else {
		print;
	    }
	}
    } else {
	print
    }
}
