#!/usr/local/bin/perl
#
# From: jablo@diku.dk (Jacob Martin Bohn Lorensen)
# Newsgroups: news.software.nntp
# Date: 18 Mar 1996 13:03:06 GMT
# Organization: Department of Computer Science, U of Copenhagen
#
# Read stdin lines of the form
# some/news/group/1234
# and add each article listed to the history file using
# ctlinnd addhist .........
#
# Posting date comes from Date: header
# Expire date comes from Expire: header (if present)
# Arrival date comes from Date: header + 2 hours :-(
# Paths comes from Xref: header.
#

$NEWSSPOOL="/usr/spool/news";
$CONVDATE="/usr/lib/news/bin/convdate";
$DEFAULT_DELIVERY_TIME=2*60*60; # seconds
$CTLINND="/usr/lib/news/bin/ctlinnd";

chdir $NEWSSPOOL;

print "## To add any articles found in the news spool and not in\n";
print "## The history files, feed the following lines to your shell\n";
print "\n";

while (<>) {
    chop;
    ($msg_id, $expire_date, $posted_date, $paths) = 
	&parse_article($_);
    next if ($msg_id eq "ERROR"); # File might have gone
    next if defined($articles{$msg_id}); # Process each msg-id once only!
    $articles{$msg_id} = 1;
    if ($expire_date != "") {
	$expire_time = &convdate($expire_date);
    } else {
	$expire_time = 0;
    }
    $posted_time = &convdate($posted_date);
    $arrive_time = $posted_time + $DEFAULT_DELIVERY_TIME;
    print "$CTLINND addhist '$msg_id' " .
	"$arrive_time " . 
	    "$expire_time " . 
		"$posted_time " .
		    "'$paths'" . "\n";
}
exit 0;

#
# Convert date 
sub convdate {
    local($date) = @_;

    open (CONVDATE, $CONVDATE . " -n " . "'$date'" . "|") ||
	die "Cannot exec $CONVDATE";
    $cd = <CONVDATE>; chop($cd);
    close CONVDATE;
    return $cd;
}

sub parse_article {
    local($art) = @_;

    # We only want to process real articles. No dirs or...
    (-f $art && open(ART, $art)) || return ("ERROR");
    $expire = "";
    $paths = $art;
    while (<ART>) {
	chop;
	last if $_ eq "";
	/^Message-ID: (<.*>)/ && ($id = $1);
	/^Date: (.*)$/ && ($posted = $1);
	/^Expires: (.*)$/ && ($expire = $1);
	/^Xref: diku.dk (.*)$/ &&
	    ($paths = $1) &&
		($paths =~ s![.:]!/!g);
    }
    close(ART);
    return ($id, $expire, $posted, $paths);
}
