#!/usr/bin/perl

#
# Convert ezmlm mail archives into HTML pages.
#   by T.Kusano 2000/3/7
#   <http://www.asahi-net.or.jp/~AE5T-KSN/>
#

#
# ex) convert 'foo-list@example.com'
#    % ls -l ~foo/.qmail-list
#    ..(*snip*).. /home/foo/.qmail-list -> /home/foo/list/editor
#    % ls -CF ~foo/list/archive
#    0/ 1/
#    % ezmlm2web.pl ~foo/list/archive /documentroot/ml/foo-list foo-list
#

use lib qw "/usr/share/mhonarc";
use strict;
use vars qw($RCFILE);

$RCFILE = '/usr/local/etc/mhonarc.rc';

die "usage: $0 archive-dir output-dir title-prefix\n" if @ARGV != 3;

&main(@ARGV);

sub main {
    my ($archivedir, $outputdir_prefix, $title_prefix) = @_;
    
    umask 022;
    
    ## Load main MHonArc library
    require 'mhamain.pl' || die "ERROR: Unable to require mhamain.pl\n";
    &mhonarc::initialize();

    -d $outputdir_prefix || die "$outputdir_prefix: not exist\n";

    my %index = ();

    opendir DH1, $archivedir or die "$archivedir: opendir: $!\n";
    while (defined (my $n = readdir DH1)) {
	&scansubdir("$archivedir/$n", \%index) if $n =~ /^\d+$/;
    }
    closedir DH1;

    foreach my $key (sort keys %index) {
	my $m = $index{$key};
	my ($year, $month) = split /,/, $key;
	printf "%04d/%02d\n", $year, $month;
	my $outputdir = sprintf("%s/%04d%02d",
				$outputdir_prefix, $year, $month);
	mkdir $outputdir, 0755;

	my $title = sprintf("%s : %04d/%02d : Date Index",
			    $title_prefix, $year, $month);
	my $ttitle = sprintf("%s : %04d/%02d : Thread Index",
			     $title_prefix, $year, $month);
	foreach my $file (sort {$m->{$a} <=> $m->{$b}} keys %$m) {
	    &mhonarc::process_input(
				    '-add',
				    '-quiet',
				    '-rcfile', $RCFILE,
				    '-outdir', $outputdir,
				    '-title',  $title,
				    '-ttitle', $ttitle,
				    '-stdin',  $file);
	}
    }
}

sub scansubdir {
    my ($dir, $idx) = @_;

    my ($mtime, $key, $full, $y, $m);
    opendir DH2, $dir or die "$dir: opendir: $!\n";
    while (defined(my $f = readdir DH2)) {
	next unless $f =~ /^\d+$/;
	$full = "${dir}/$f";
	$mtime = (stat $full)[9];
	($y, $m) = (localtime $mtime)[5, 4];
	$key = sprintf "%04d,%02d", $y+1900, $m+1;
	if (!defined($idx->{$key})) {
	    my %initial = ($full=>$mtime);
	    $idx->{$key} = \%initial;
	} else {
	    $idx->{$key}->{$full} = $mtime;
	}
    }
    closedir DH2;
}

# end of script
