#!/usr/athena/bin/perl

require "lib.pl";

$cf = "rkive.cf";
$infile = "list";
%matches = ();

$oldselect = select(STDOUT); $| = 1; select($oldselect);

while ($_ = $ARGV[0], /^-/) {
    shift;
    if (/^-db$/) {
	die "Missing argument to \"-db\".\n" if (! @ARGV);
	$infile = shift;
	next;
    }
    if (/^-out$/) {
	die "Missing argument to \"-out\".\n" if (! @ARGV);
	$cf = shift;
	next;
    }
    die "Unknown argument \"$_\".\n";
}

open(CF, ">$cf") || die "Opening $cf: $!\n";

print "Reading...\n";

@records = &lopip'read_data($infile);

print "Frobbing...\n";

while ($_ = shift @records) {
    next if &lopip'is_special($_, 'subject');
    $newsgroups = &lopip'field_value($_, 'newsgroups');
    warn "Newsgroups line contains whitespace:\n$_"
	if ($newsgroups =~ /\s/);

    if ($newsgroups =~ /,$/) {
	$newsgroups =~ s/,$//;
	warn "Newsgroups line contains comma at end:\n$_";
    }

    @ngs = split(/,[\t ]*/, $newsgroups);
    @sub = (&lopip'field_values($_, 'subject'),
	    &lopip'field_values($_, 'archive-subject'));
    for $sub (@sub) {
	# rkive can't handle multi-line subjects yet
	$sub =~ s,\n.*,,g;
	$sub =~ s,([\[\]\^\-\?\\\"\#]),\\$1,g;
	while ($sub =~ /\*\*+/) {
	    local($left, $str, $right) = ($`, $&, $'); #`)
	    $str =~ s/\*/\\\*/g;
	    $sub = $left . $str . $right;
	}
	for $ng (@ngs) {
	    if ($matches{$ng}) {
		$matches{$ng} .= " \\\n\tor subject glob-matches \"$sub\"";
	    }
	    else {
		$matches{$ng} = "MATCH: subject glob-matches \"$sub\"";
	    }
	}
    }
}

print "Writing...\n";

print CF "TYPE=External-Command
ARCHIVE_CMD=/rtfm/faq_archiver/save-faq
MAIL=faqs
OWNER=lopipusr
GROUP=faqs
MODE=0664
NNTP=news.mit.edu
PROBLEMS=/rtfm/faq_archiver/problems
MAXARTFILE=/rtfm/faq_archiver/.archived_max

";

foreach $newsgroup (keys %matches) {
    print CF "\$\$$newsgroup\n\tBASEDIR: /rtfm/faq_archiver\n";

    print CF "\t$matches{$newsgroup}\n" 
	if ($newsgroup !~ /^[^.]+\.answers$/);

    print CF "\n";
}

close(CF);

exit 0;
