#!/usr/bin/perl
##
##  MetaELM -- ELM frontend
##  Copyright (c) 1997 Ralf S. Engelschall, All Rights Reserved.
##

require 5.003;

use Date::Parse;
use Date::Format;

#
#   configuration
#
$melmrc = "$ENV{'HOME'}/.melmrc";

#
#   read rc-file
#
@MAILFOLDER = ();
open(RC, "<", "$melmrc") || die "** mElm:Error: no \"$melmrc\" found. Please create one first.\n";
while (<RC>) {
    next if (m|^\s*$|);
    next if (m|^\s*#.*$|);
    if (m|^\s*(/\S+)\s+(.+?)\s*$|) {
        push(@MAILFOLDER, { FOLDER => $1, NAME => $2 });
    }
    else {
        print STDERR "** mElm:Error: bad RC-file entry:\n";
        print STDERR "** mElm:Error: $_";
        exit(1);
    }
}
close(RC);


sub update_entry {
    ($entry) = @_;
    ($name, $folder) = ($entry->{NAME}, $entry->{FOLDER});
    @F = `from -f $folder`;
    $time = $F[$#F];
    $time =~ s|^From\s+\S+\s+(.+)\s*|$1|;
    $time = str2time($time);
    $entry->{TIME} = $time;
    $entry->{MAILS} = $#F+1;
}
foreach $entry (@MAILFOLDER) {
    update_entry($entry);
}

#
#   processing loop
#
$pos = 4;
while (1) {
    $L = '"" ' .
         '"Available Folders: '. sprintf("%d", $#MAILFOLDER + 1) .'" ' .
         '"" ';
    $n = 1;
    foreach $entry (@MAILFOLDER) {
        ($name, $folder, $time, $mails) =
            ($entry->{NAME}, $entry->{FOLDER}, $entry->{TIME}, $entry->{MAILS});
        $arg .= sprintf("%2d  %-20s  (%3d) %s %2d <S:elm -f $folder>", $n++, $name, $mails, time2str("%a", $time), time2str("%d", $time));
        $arg =~ s|'|\'\\\'\'|g;
        $L .= "'$arg' "
    }
    $L .= "'' ";
    $L .= "'_____________________________________________________' ";
    $L .= "'' ";
    $L .= "'Help: <up>,<down> .......... browse folder list' ";
    $L .= "'      <return>,<right> ..... select folder (run ELM)' ";
    $L .= "'      q,<left> ............. quit' ";

    $rc=`exec iselect -n "MetaELM 1.0.0" -t "Electronic Mail Folders" -p$pos -P $L`;
    if ($rc eq '') {
        exit(0);
    }
    $rc =~ m|^(\d+):(.*)|;
    ($pos, $cmd) = ($1, $2);
    system($cmd);

    update_entry($MAILFOLDER[$pos-4]);
}
