#!/usr/bin/perl
use strict;
use warnings;

use Digest::MD5 qw(md5 md5_hex md5_base64);
use MIME::Parser;
use MIME::Entity;
use MIME::Body;
use Getopt::Long;

use lib qw(Core);
use lib qw(Classes);

use Configuration;
use LocalConfiguration;

use GroupsManager;
use Distribution;
use JobsManager;
use Logger;
use Email;


my $SCRIPTNAME = 'responser.pl';

my $logger = new Logger();

my $input_file = '';

my $isparams = GetOptions(
	"file|f=s"         => \$input_file
);


my $EMAIL;
my $INPUT;
if($input_file ne '') {
    open($INPUT, $input_file);
    $EMAIL = $INPUT;
} else {
    $EMAIL = \*STDIN;
}

# generate unique id for predictionfile

my $message_filename = '';
my $message_file = '';

my $uid = md5_hex(sprintf("casp9%s%d", join(':', localtime()), rand(9999))); # generate unique uid for response and request

$message_filename = sprintf("%s.message", $uid);
$message_file = sprintf("%s/%s", $LOCAL_CONFIG->{META_MESSAGES_DIR}, $message_filename);



# save original email message to file

my $content = '';
if(open(MESSAGE, sprintf("> %s", $message_file))) {
	while(<$EMAIL>) {
	    print(MESSAGE $_);
		
		$content .= $_;
	}
	close(MESSAGE);
} else {
	$logger->error($SCRIPTNAME, sprintf("Email message wasn't saved! File: %s", $message_file));
	exit;
}

$logger->info($SCRIPTNAME, sprintf("New job file received, UID: %s", $uid));

open(my $SAVED_MESSAGE, $message_file);

# process email
my $parser = new MIME::Parser();
$parser->ignore_errors(1);
$parser->output_to_core(1);

my $entity = $parser->parse($SAVED_MESSAGE);
my $error = ($@ || $parser->last_error);

my $header = $entity->head;

my $sender_email = $header->get('From');
my $subject = $header->get('Subject');
my $body = join('',  @{$entity->body});

# remove trailing whitespace from body
$body =~ s/\s*\n+$//s;

my $EMAIL_REGEXP = '[\w\-\.\_]+@[\w\-\.\_]+';
if($sender_email =~ /\s*($EMAIL_REGEXP)\s*/) {
	$sender_email = $1;
}

chomp($sender_email);

# Hot fix for resume@allcadnw.com
if($sender_email eq 'resume@allcadnw.com') {
        $logger->error($SCRIPTNAME, "Got email resume\@allcadnw.com...");
        exit;
}

$logger->info($SCRIPTNAME, sprintf("Sender email: %s", $sender_email));

my $target = '';
if(($subject =~ /(T\d{4})/) || ($subject =~ /(T[Rracspx]\d{3})/)) {
	$target = $1;
} else {
	$logger->error($SCRIPTNAME, "No target mentioned in email subject!");
	exit;
}


my $distribution = new Distribution();
my $job_uid = $distribution->receive_response_from_common_email($sender_email, $target, $subject);

if($job_uid eq '') {
	$logger->error($SCRIPTNAME, "Can't find proper job for sender!");
	exit;
}

if(0 == system(sprintf("cp -p %s %s/%s.response", $message_file, $LOCAL_CONFIG->{RESPONSE_DIR}, $job_uid))) {
	system(sprintf("chmod a+r %s/%s.response", $LOCAL_CONFIG->{RESPONSE_DIR}, $job_uid));
	
#	Email::send_email($LOCAL_CONFIG->{SUPPORT_EMAIL}, $LOCAL_CONFIG->{SUPPORT_EMAIL_ADMIN}, "", "", sprintf("Response received %s", $sender_email), $content);
	$logger->info($SCRIPTNAME, sprintf("Copy file %s to responses %s", $uid, $job_uid));
} else {
	#$logger->error($SCRIPTNAME, "Message wasn't moved to responses!");
	exit;
}

close($SAVED_MESSAGE);
