#! /usr/local/bin/perl

$spooldir = '/proj/WWW/htdocs/auto-whatsnew';
$spoolhtml = 'http://www.wide.ad.jp/auto-whatsnew';
$sequencefile = "$spooldir/seq";
$intindexfile = "$spooldir/idx";
$indexfile = "$spooldir/idx.html";
@members = ('itojun@mt.cs.keio.ac.jp', 'itojun@csl.sony.co.jp',
	'shigeya@foretune.co.jp');

chop($date = `date`);

#open(IN, "nkf -s - |");
open(IN, "<&STDIN");

# incorporate headers
$s = select(IN); $/ = "\n\n"; select($s);
$headers = <IN>;
$headers =~ s/\n\s+/ /g;
@headers = split("\n", $headers);

# security check
$from = join(' ', grep(/^from:/i, @headers));
$from =~ s/From:\s+/ /;
$ok = 1;	# disable security check
#$ok = 0;
foreach $i (@members) {
	if ($from =~ /$i/) {
		$ok = 1;
		break;
	}
}
if (! $ok) {
	exit 0;
}
open(TEST, ">/tmp/hoge");
print TEST "this is test\n";
close(TEST);


# incorporate sequence number
open(SEQ, "<$sequencefile");
chop($sequence = <SEQ>);
close(SEQ);
open(SEQ, ">$sequencefile");
print SEQ ++$sequence . "\n";
close(SEQ);

#open(OUT, "| nkf > $spooldir/$sequence.html");
open(OUT, "> $spooldir/$sequence.html");

print OUT "<HTML><BODY><PRE>\n";
print OUT ($subject = join("\n", grep(/^subject:/i, @headers)) . "\n");
$subject =~ s/Subject:\s*//ig;
$subject =~ s/\n+/ /g;
$subject =~ s/\s+$//;
print OUT join("\n", grep(/^date:/i, @headers)) . "\n";
print OUT join("\n", grep(/^from:/i, @headers)) . "\n";
print OUT join("\n", grep(/^cc:/i, @headers)) . "\n";
print OUT join("\n", grep(/^message-id:/i, @headers)) . "\n";
print OUT join("\n", grep(/^in-reply-to:/i, @headers)) . "\n";

# output body
$s = select(IN); $/ = "\n"; select($s);
while (<IN>) {
	print OUT;
}
print OUT "</PRE></BODY></HTML>\n";
close(OUT);
close(IN);

# create index file for internal use
open(INTIDX, ">>$intindexfile");
print INTIDX "<LI> $date: <A HREF=$spoolhtml/$sequence.html>$subject</A>\n";
close(INTIDX);

# create index file
open(IDX, ">$indexfile");
print IDX "<HTML><BODY><UL>\n";
open(INTIDX, "<$intindexfile");
while (<INTIDX>) {
	print IDX;
}
close(INTIDX);
print IDX "</UL></BODY></HTML>\n";
close(IDX);

exit 0;
