#!/usr/bin/perl
# create list of valid mailbox directory paths

use File::Find;

undef @directories;
undef @accounts;
undef %options;
$savetargetdir = "";
$tmpPath = shift;

open ( TMPFILE, ">$tmpPath" ) || print STDERR "problem opening $tmpPath\n";
while ( $account = shift ) {
    push @accounts, $account;
}
$options{'wanted'} = \&wanted;
$options{'no_chdir'} = 1;
find(\%options, @accounts);
foreach $dir (@directories) {
    &doDirectory ($dir);
}
close TMPFILE;

sub wanted {
    local($file) = $File::Find::name;
#    $file = s/^.+\/([^\/]+)$/$1/;
    if ( $file =~ /^\./ ) { return; }
    if ( (-d $File::Find::name) ) {
        push @directories, $File::Find::name;
    }
}

sub doDirectory {
    local($targetdir) = @_;
    local(@files);
    local($file) = "";
    opendir(NEXTDIR, "$targetdir") || print STDERR "doDirectory: problem opening $targetdir\n";
    @files = readdir(NEXTDIR);
    closedir NEXTDIR;
    local($gotFiles) = 0;
    foreach $file ( @files ) {
#        if ( $file =~ /^\./ ) { next; }
        if ( (-d "$targetdir/$file") ) {
            next;
        }
        if ( $file !~ /\.emlx/ && $file ne "mbox" ) { next; }
	$gotFiles = 1;
	last;
    }
    if ( $gotFiles || $targetdir =~ /Messages$/ ) {
	$targetdir =~ s/\/Messages$//;
	if ( $targetdir ne $savetargetdir ) {
	    print TMPFILE "$targetdir\n";
	}
	$savetargetdir = $targetdir;
    }
}
