#!/usr/local/bin/perl
#
# vscan :: Virtual scan for Mew that give a single view for multiple folders
#
# Auther:  Kazuhiko Yamamoto <kazu@is.aist-nara.ac.jp>
# Version: 0.2 
# Created: June 17, 1995
# Revised: June 18, 1995
# Modified: July 25, 1995  	Shiegya Suzuki <shigeya@foretune.co.jp>
# Modified: November 28, 1995	Shigeya Suzuki <shigeya@foretune.co.jp>
# Modified: December 12, 1995	Shigeya Suzuki <shigeya@foretune.co.jp>
#
# Usage:
#   vscan [--pick pick_patterns] [--scan scan_options] +folder [+folder ...]
#
# In the end of line, "^M" for selective-display and folder/message follow. 

chop($mailfolder = `mhpath +`);
$folderalias = "$mailfolder/FolderAlias";

$pick = 0;
$scan = 0;
chop($pwd = `pwd`);

#
# scan FolderAlias file
#
if (-e $folderalias ) {
    open(F,$folderalias) || die "Can't open $folderalias: $!";
    while(<F>) {
	next if /^#/;
	chop;
	s/,/ /g; # change comma to space
	s/\s+/ /g; # remove extra spaces
	s/\s+:\s+/:/g; # too.
	if ((($foldername, $folderlist) = split(/:/)) == 2) {
	    $foldername =~ s/ //g; # remove space from name
	    $foldername =~ s/\+//g; # remove + from name
	    $folderlist =~ s/^\s+//g;
	    $folderalias{$foldername} = $folderlist;
	}
    }
    close(F);
}

#print "+RECENTINBOX -> ", join(',', &recurseexpand("+RECENTINBOX")), "\n";

#
# ARGV[0] must not be "0".
#
while ($_ = $ARGV[0]) {
	if ( /\+(.*)/ ) {
	    push(@folders, &recurseexpand($_));
	} elsif ( $_ eq "--pick") {
		$pick = 1;
		$scan = 0;
	} elsif ( $_ eq "--scan") {
		$pick = 0;
		$scan = 1;
	} elsif ($scan) {
		if ($scanargs) {
			$scanargs = $scanargs . " " . $_;
		} else {
			$scanargs = $_;
		}
	} elsif ($pick) {
		if ($pickargs) {
			$pickargs = $pickargs . " " . $_;
		} else {
			$pickargs = $_;
		}
	}
	shift(@ARGV);
}

$num = 1;
while (@folders) {
	$messages = "";    
	if ($pickargs) {
		open(PICK, "pick $pickargs $folders[0] |");
		while(<PICK>) {
			chop;
			if ($messages) {
				$messages = $messages . " " . $_;
			} else {
				$messages = $_;
			}
		}
	} else {
		$messages = "all";
	}
	if ($messages) {
		open(FOLDER, "scan $scanargs $folders[0] $messages |");
		while(<FOLDER>) {
			chop;
			if (/ *([0-9]+)(.*)/) {
				# virtual number
				# contents
				# ^M for selective-display
				# +folder/message
				printf "%4d%s\015 %s %s\n", 
					$num, $2, $folders[0], $1;
			}
			$num ++;
		}
	}
	shift(@folders);
}

sub expandone {
    local($s) = shift;
    local(@r) = ();

    chdir($mailfolder);
    foreach (split(/\s+/,$s)) {
	if (m/[\*\?\{\}\[\]]/) {	# has wild match
	    s/^\+//;
	    foreach (<${_}>) {		# perl4 don't have map()!
	    	push(@r, "+$_");
	    }
	}
	else {
	    push(@r, "+$_");
	}
    }
    chdir($pwd);
    return @r;
}

sub recurseexpand {
    local($s) = shift;
    local(@r) = ();

    if ($s =~ s/^\+//g) {
	if (defined($folderalias{$s}) ne "") {
	    foreach (split(/\s+/, $folderalias{$s})) {
		push(@r, &recurseexpand($_));
	    }
	    return @r;
	}
    }
    return &expandone($s);
}

# End of vscan
