#!/usr/bin/perl
# @(#) mail2news Version 1.0
# Pipe mail messages into news server
#
# Copyright (c) 1996 Gaspar Sinai <gsinai@gol.com>
# I dont want to make the compication long: please read the separate
# file called COPYING
#
# usage: mail2news  [-g newsgroup] newspost_command
# This program is normally used with newspost command. It creates the
# batchfile and sets the -f argument. The rest is up to newspost.

#
# Command line arguments
#
while ($#ARGV >=0)
{
	if( $#ARGV > 0 && $ARGV[0] eq "-g")
	{
		if ( defined (@NEWSGROUP))
		{
			@NEWSGROUP=(@NEWSGROUP, ",", $ARGV[1]);
		}
		else
		{
			@NEWSGROUP=("Newsgroups: ", $ARGV[1]); 
		}
		shift;shift;
	}
	else
	{
		last;
	}
}
if ($#ARGV < 1)
{
	print <<EOD;
usage: mail2news [-g newsgroup] newspost_command args [ args..]
EOD
	exit (255);
}

if ( defined (@NEWSGROUP))
{
	@NEWSGROUP=(@NEWSGROUP, "\n");
}

#
# Processing messages
#
while (<STDIN>)
{
	@ARTICLE=(@ARTICLE, $_);
	@ARTICLE=(@ARTICLE, @NEWSGROUP) if ($#ARTICLE==0 && defined(@NEWSGROUP));
}

#
# Making batchfile for posting
#
$TMPFILE="/tmp/mail2news-tmp.$$";
$BATCHFILE="/tmp/mail2news-batch.$$";

die "$0: Can not open $TMPFILE.\n" unless (open (TMPF, ">$TMPFILE"));
print TMPF @ARTICLE;
close (TMPF);

unless (open (BATF, ">$BATCHFILE"))
{
	unlink $TMPFILE;
	die "$0: Can not open $BATCHFILE.\n" unless (open (BATF, ">$BATCHFILE"));
}
print BATF "$TMPFILE\n";
close (BATF);

$COMMAND=$ARGV[0];
shift;
@ARGUMENTS=@ARGV;

#
# Posting the article
#
unless (open (POST, "| $COMMAND -f $BATCHFILE @ARGUMENTS"))
{
	unlink ($TMPFILE, $BATCHFILE);
	die "$0: Can not execute @ARGV -f $BATCHFILE.\n";
}
print POST @ARTICLE;
close (POST);

if ($?!=0)
{
	unlink ($TMPFILE, $BATCHFILE);
	die "$0: Could not post mail.\n";
}
unlink ($TMPFILE, $BATCHFILE);
exit 0;

