#!/usr/bin/perl

# $Id: paypal_send,v 1.7 2011/12/02 02:36:28 gilles Exp gilles $

use strict;
use warnings;
use Getopt::Long;
use MIME::Lite;

my (
	$help,
	$debug,
	$send,
	$subscribe,
);

my $numopt = scalar(@ARGV);
my $opt_ret = GetOptions(
	"help"		=> \$help,
	"debug!"	=> \$debug,
	"send!"	        => \$send,
	"subscribe!"	=> \$subscribe,
);

usage() and exit if ($help or ! $numopt or ! $opt_ret) ;

my @reply = <>;
my %header;

while (my $line = shift @reply) {
	#print $line;
	chomp($line);
	last if ($line =~ /^$/) ;
	my($blank, $key, $value) = split /^(.+?:)\s*/, $line;
	#print "[$key] [$value]\n";
	$header{$key} = $value;
}

my $data = join('', @reply);

#print "[", $data, "]\n";

my $message = MIME::Lite->new();
$message->attr("content-type" => "text/plain");
$message->attr("content-type.charset" => "UTF-8");

$message->build(%header);
$message->build(Data => $data);
$message->print(\*STDOUT);

my $dest = $header{ 'To:' } ;

if ( $send ) {
	$message->send ;
	print "\nSent to $dest\n" ;
}

if ( $subscribe ) {
	print "\necho '$dest' | add_members --regular-members-file=- --welcome-msg=y imapsync_update\n" ;
        my $out = `echo '$dest' | sudo add_members --regular-members-file=- --welcome-msg=y imapsync_update` ;
	print $out ;
	print "Subscribed $dest\n" ;
}



sub usage {
        print <<EOF;

usage: $0 [options] file

--help              : print this help message
--debug             : verbose output
--send              : send message

Examples: 
$0 file
$0 --send file
EOF
}

