#!/usr/local/bin/perl5
#
# 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.
#

$ego = "X-Reflected-By: snarfnews conva2m 1.0\n";
push(@diefields, "x-reflected-by");
push(@skipfields, "path", "xref", "newsgroups");

# create list of extra fields to skip/die on
while ($ARGV[0] =~ /^-/o)
{
    $flag = shift(@ARGV);

    if ($flag =~ /^-skip-(\S+)$/o)
    {
	$field = $1;
	$field =~ tr/A-Z/a-z/;
	push (@skipfields, $field);
    }
    elsif ($flag =~ /^-die-(\S+)$/o)
    {
	$field = $1;
	$field =~ tr/A-Z/a-z/;
	push (@diefields, $field);
    }
    elsif ($flag eq "-debug")
    {
	$debug++;
    }
}

warn "skip=(@skipfields)\n" if ($debug);
warn "die=(@diefields)\n" if ($debug);

# reprocess header
@header = ();
$doneprint = 0;

while (<STDIN>)
{
    # break to body on blank line
    if (/^\s*$/)
    {
	if ($#ARGV >= 0)
	{
	    foreach (@ARGV)
	    {
		push(@header,  "$_\n");
	    }
	}
	push(@header,  $ego);
	push(@header, $_);
	last;
    }

    # continuation lines
    if (/^\s/oi)
    {
	if ($doneprint)
	{
	    push(@header, $_);
	}
	next;
    }

    # fields to die on
    if (/^([^:]+):/)
    {
	$thisfield = $1;
	$thisfield =~ tr/A-Z/a-z/;

	if (grep {$_ eq $thisfield} @diefields)
	{
	    warn "conva2m: contains pathological header: $thisfield\n" if ($debug);
	    exit 0
	}

	if (grep {$_ eq $thisfield} @skipfields)
	{
	    $doneprint = 0;
	    next;
	}
    }
    else
    {
	die "conva2m: illegal header: $_";
    }

    # fields to keep verbatim
    if (/^from:/oi ||
	/^subject:/oi ||
	/^date:/oi ||
	/^reply-to:/oi ||
	/^organization:/oi ||
	/^lines:/oi ||
	/^references:/oi ||
	/^message-id:/oi ||
	/^mime/oi ||
	/^content/oi ||
	/^x-/oi)
    {
	push(@header,  $_);
    }
    else
    {
	push(@header,  "X-$_");
    }

    $doneprint = 1;
}

print @header;

print while (<STDIN>);

exit 0;
