#!/usr/bin/env perl
our $VERSION = "0.1";

###############################################################################
### Variables #################################################################
###############################################################################
use vars qw( $PROG );

$PROG = "mutt -F $ENV{HOME}/.config/mutt/muttrc.news";

###############################################################################
### main() ####################################################################
###############################################################################

use lib '/home/tskirvin/dev/newslib';
use News::Article;
use News::Article::Clean;
use strict;
use File::Temp qw/ tempfile tempdir /;

my $dir = tempdir( CLEANUP => 1 );
my ($fh, $temp) = tempfile( DIR => $dir );

my $article;
my $file = shift @ARGV;
if ($file) { 
  die "No such file: $file\n" unless (-r $file);
  $article = News::Article->new($file, 1024 * 1024, 1024 * 64);
  die "Couldn't read article: $!\n" unless $article;
} else {
  die "Not supported right now - use 'complain'"
}

my $from = $article->header('from') || "";
   $from = $article->clean_from( $from );

my $subject = $article->header('subject') || "(no subject)";
   $subject = "Re: $subject";
   $subject = $article->clean_subject( $subject );

my $msgid = $article->header('message-id') || "";

my $respond = $article->header('reply-to') || $article->header('from');

my @users;
if (my $user = $article->header('x-complaints-to')) { push @users, $user }
if (my $user = $article->header('x-poster-complaints-to')) { push @users, $user }
if (my $trace = $article->header('x-trace')) {
  $trace =~ s/^\s*(\S+)\s+.*/$1/;
  push @users, "abuse\@$trace"
}
push @users, "admin\@unknown.site.invalid" unless scalar @users;

print $fh "From: Tim Skirvin <tskirvin\@killfile.org>\n";
print $fh "Reply-To: tskirvin\@killfile.org\n";
print $fh "In-Reply-To: $msgid\n" if $msgid;
print $fh "Subject: Abuse from your Usenet server\n";
print $fh "To: ", join(", ", @users), "\n" if @users;
print $fh "\n";
print $fh "     [insert boilerplate here]\n\n";
print $fh "$from writes:\n";
foreach ($article->rawheaders) { print $fh "> $_\n"; }
print $fh "\n";
foreach ($article->body) { print $fh "> $_\n"; }

my $cmd = "$PROG -H $temp -a $file";
print "$cmd\n";
my $response = system($cmd);
