#!/usr/local/bin/perl5 -s
#
# This file is part of SnarfNews
# Copyright (C) 1991,1992,1993,1994,1995,1996 Alec Muffett
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of version 2 of the GNU General Public License as
# published by the Free Software Foundation
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#

$feeds = "$ENV{SNARFCONF}/feeds";

sub tidy
{
    $thing = shift;
    $thing =~ s/^\s+//o;
    $thing =~ s/\s+$//o;
    $thing;
}

unless (open(FEEDS, $feeds))
{
    die "$0: open: $feeds: $!\n";
}

while ($line = <FEEDS>)
{
    next if ($line =~ /^\#/o);
    next if ($line =~ /^\s*$/o);

    $line =~ s/\s+$//o;

    while ($line =~ /\\$/o)
    {
	$line =~ s/\\//o;
	$line .= <FEEDS>;
	$line =~ s/\s+$//o;
    }

    ($name, $reader, $writer) = split(/:/, $line, 3);

    $name = &tidy($name);

    unless ($#ARGV < 0)
    {
	next unless grep {$_ eq $name} @ARGV;
    }

    unless ($nolock)
    {
	$lockcookie = "runfeed.$name";

	warn "runfeed: locking $lockcookie\n";

	system("lock", $lockcookie);

	if ($?)
	{
	    warn "runfeed: could not lock $lockcookie\n";
	    next;
	}
    }

    $reader = &tidy($reader);
    $writer = &tidy($writer);

    warn "runfeed: doing: $name\n" if ($debug);

    if ($writer eq "")
    {
	warn "runfeed: running: $reader\n" if ($debug);
	system($reader) unless ($debug2);
	warn "runfeed: $name: $reader: exit status $?\n" if ($?);
    }
    else
    {
	$tmp = "$ENV{SNARFRUN}/runfeed.$name";

	warn "runfeed: reader: $reader\n" if ($debug);

	open(OSTDOUT, ">&STDOUT");
	open(STDOUT, ">$tmp");
	system($reader) unless ($debug2);
	warn "runfeed: $name: $reader: exit status $?\n" if ($?);
	open(STDOUT, ">&OSTDOUT");
	close(OSTDOUT);

	$size = (-s $tmp);

	warn "runfeed: reader: spooled $size bytes\n" if ($debug);

	if ($size)
	{
	    warn "runfeed: writer: $writer\n" if ($debug);

	    open(OSTDIN, "&STDIN");
	    open(STDIN, $tmp);
	    system($writer) unless ($debug2);
	    warn "runfeed: $name: $writer: exit status $?\n" if ($?);
	    open(STDIN, "&OSTDIN");
	    close(OSTDIN);
	}

	unlink($tmp);
    }

    unless ($nolock)
    {
	system("unlock", $lockcookie);

	if ($?)
	{
	    die "runfeed: could not unlock $lockcookie\n";
	}
    }
}

close(FEEDS);

exit 0;
