#!/usr/bin/perl
#
#NAME
#  List - produce list of email messages in current folder
#
#SYNOPSIS
#  List [+folder] 
#
#REQUIRES

	$LNAM = $ENV{'LOGNAME'} || $ENV{'USER'};
	$HOME = $ENV{'HOME'} || "/home/$LNAM";
	@INC = ($HOME, "$HOME/mh","$HOME/sh",@INC);
	require 'jcmh.pm';
	use MIME::Base64();		# Decode base-64 text
	use MIME::QuotedPrint;	# Decode quoted-printable text

#DESCRIPTION
#  This lists messages in an mh-style Mail/folder directory.
#
#OPTIONS
#
#EXAMPLES
#
#FILES
#
#BUGS
#
#SEE ALSO
#
#AUTHOR
#  John Chambers <jc@trillian.mit.edu>
#  2020-10-14 Added Base64 decoding of Subject: lines, which has become common.

$| = 1;

for $a (@ARGV) {
	print "$0: Arg \"$a\"\n" if $V>2;
	if ($a =~ /^\+(\w+)$/) {
		$fldr = $1;
		print "Folder \"$fldr\" from command line.\n" if $V>2;
	} else {
		print STDERR "$P: Unrecognized arg \"$a\" ignored.\n";
	}
}
$fldr = $FLDR unless $fldr;
print "Folder \"$fldr\"\n" if $V>1;

$imax = &maxindex($MDIR,$fldr);
print "Highest index in $MDIR/$fldr is $imax.\n" if $V>1;

$ndx = &getindex($MDIR,$fldr,1);
print "Current index in $MDIR/$fldr is $ndx.\n" if $V>1;

file:
for ($i = 0; $i <= $imax; $i++) {
	unless (open(MSG,"$MDIR/$fldr/$i")) {
		printf "$MDIR/$fldr/%d doesn't exist.\n",$i if $V>2;
		printf "%3d->\n",$i	# Show missing current msg
			if $i == $ndx;
		next file;
	}
	printf "$MDIR/$fldr/%d exists.\n",$i if $V>4;
	$from = $subj = $date = '';
line:
	while ($l = <MSG>) {
		$l =~ s/[\s\r]+$//;	# Trim away white stuff
		if ($l eq '') {
			last line;
		} elsif ($l =~ /^Subj\w*:\s*(.*)/i) {
			$subj = $1 || '(unknown)';
			if ($subj =~ m/=\?UTF-8\?B\?(.+)/i) {
				$subj =  MIME::Base64::decode($1);
			} elsif ($subj =~ m/=\?utf-8\?Q\?(.+)/i) {
				$subj =  decode_qp($1);
			}
			$subj =~ s/^re:\s*re:\s*/RE: /i;
			$subj = '[no subject]' unless $subj;
		} elsif ($l =~ /^From:\s*(.*)/i) {
			$from = $1;
			if ($from =~ m/=\?utf-8\?Q\?(.+)/i) {
				$from =  decode_qp($1);
			}
		} elsif ($l =~ /^Date:\s*(.*)/i) {
			$date = $1;
		}
	}
	if ($i == $ndx) {
		&msgdesc($i,'->',$date,$from,$subj);
	} else {
		&msgdesc($i,': ',$date,$from,$subj);
	}
}
print "That's all.\n" if $V>1;

exit 0;
