#!/usr/bin/perl -w

# $Id: paypal_imapget,v 1.10 2013/08/21 22:19:35 gilles Exp gilles $

use Getopt::Long;
use Mail::IMAPClient;
use FileHandle;


my $host;
my $port = 143;
my $debugimap = 0;
my $debug = 0;
my $user;
my $password;
my $passfile;
my $folder = 'INBOX';
my @search ;
my $help;

my $numopt = scalar(@ARGV);
my $opt_ret = GetOptions(
	"host=s"	=> \$host,
	"user=s"	=> \$user,
	"password=s"	=> \$password,
	"passfile=s"	=> \$passfile,
	"folder=s"	=> \$folder,
	"search=s"	=> \@search,
	"help"		=> \$help,
	"delete!"	=> \$delete,
	"expunge!"	=> \$expunge,
	"debugimap!"	=> \$debugimap,
	"debug!"	=> \$debug,
);
usage() and exit if ($help or ! $numopt) ;

$password = (defined($passfile)) ? firstline ($passfile) : $password;

my $imap = Mail::IMAPClient->new();

$imap->Server($host);
$imap->Port($port);
$imap->Uid(1);
$imap->Peek(1);
$imap->Debug($debugimap);
$imap->connect()
  or die "Can not open imap connection on [$host] with user [$user] : $@\n";
$imap->User($user);
$imap->Password($password);
$imap->login() or die "Error login : [$host] with user [$user] : $@";

$imap->select($folder) or die "Error select folder [$folder] host [$host] user [$user] : $@";

#my @uids = $imap->search('HEADER', 'SUBJECT',"=?windows-1252?Q?Avis_de_r=E9ception_d=27un_paiement?=");
#my @uids = $imap->search('HEADER', 'Sender','sendmail@paypal.com');
#my @uids = $imap->search('TEXT', 'PP341');
print "@search\n" ;
@search = ('TEXT', 'PP341') if not @search ;
my @uids_01 = $imap->search('HEADER', 'Return-Path','<payment@paypal.com>', @search );
my @uids_02 = $imap->search('HEADER', 'Return-Path','<member@paypal.fr>', @search );
my @uids_03 = $imap->search('HEADER', 'Return-Path','<member@paypal.com>', @search );
my @uids = ( @uids_01, @uids_02, @uids_03 ) ;
print "Search: [@uids]\n";

foreach $msg (@uids) {
	my $msg_id = $imap->get_header( $msg, "Message-Id" );
	$debug and print "$msg_id\n";
	my $msg_code = format_msg_id($msg_id);
	my $file = "$msg_code";
	if (-f $msg_code and -f "../msg_id/$msg_code") {
		$debug and print "Already have $msg_code $msg\n";
		next;
	}
	print "writing message $msg to $file\n";
	unlink($file);
	if ($imap->message_to_file($file, $msg)) {
		$imap->delete_message($msg) if $delete;
		$imap->expunge() if $expunge;
	}else{
		print "Error writing $file: $@\n";
	}
	write_to_file("../msg_id/$msg_code", $msg_id);
}

$imap->logout();


sub usage {
        print <<EOF;

usage: $0 [options]

Several options are mandatory. 

--host       <string> : imap server. Mandatory.
--user       <string> : user to login. Mandatory.
--password   <string> : password for the user1. Mandatory.
--delete              : mark messages well dumped as deleted
--expunge             : expunge folder.

Example: 
$0 \\
   --host imap.troc.org --user foo --password secret
EOF
}

sub  firstline {
        # extract the first line of a file (without \n)

        my($file) = @_;
        my $line  = "";
        
        open FILE, $file or die("error [$file]: $! ");
        chomp($line = <FILE>);
        close FILE;
        $line = ($line) ? $line: "error !EMPTY! [$file]";
        return $line;
}

sub format_msg_id {
	my $msg_id = shift;
	
	$msg_id =~ tr/a-zA-Z0-9/_/cs;
	$debug and print "$msg_id\n";
	return($msg_id);
}

sub write_to_file {
	my $file = shift;
	my $string = shift;
	
	$fh = FileHandle->new("> $file");
	if (defined $fh) {
		print $fh $string;
		$fh->close;
	}
}
