#!/usr/local/bin/perl5.6.0


######################################################
# Tue May 13 18:14:24 BST 2003
# dn1 fix-it script for missing exoseq_readinfo reads
######################################################
use strict;
use sql_engine;
#use SDTable;
use Data::Dumper;
use Getopt::Long;
use Mail::Mailer;


#################
# Database setup
#################

#A connection to snp
my $database1 = 'exoanalysis';
my $statements = statements->new($database1);
$statements->default_sql_lib_path('/usr/local/badger/bin/');
$statements->load_sql_lib(["exo_fix_new_snp.sql_lib::all"]);

# A connection to tracking
my $database2 = 'reports';
my $statements2 = statements->new($database2);
$statements2->default_sql_lib_path('/usr/local/badger/bin/');
$statements2->load_sql_lib(["exo_fix_new_cas.sql_lib::all"]);


###############
# Mail message
###############
my $mail_message;

my $mode;
my ($help);
GetOptions (
	    "mode=s"     => \$mode,      # The category required
#	    "d=s"     => \$department,             # The department required (overrides category)
#	    "s=s"     => \$sumtrim,                # If specified, trims the summary down to the desired length
#	    "notable" => \$notable,
	    "h"       => \$help,
	    
	    );


#################
# -h (help) info
#################
if ($help){
    die "No help is available...\n";
}

if ( ($mode ne "report") && ($mode ne "update") ){
    $mode = "report";
}

&add_2_mail("---------------------------------------------------------");
&add_2_mail("Running from cron on genesis");
&add_2_mail("Program running in $mode mode");
&add_2_mail("\n\n If you run this program in update mode *BE CAREFUL*\n You need to ensure that no ExoSeq data is currently being processed !\n\n");
&add_2_mail("---------------------------------------------------------");



########################################
# Find 'missing' EXOSEQ_READINFO entries
########################################
my @missing_seqreads;
my $count = 0; 
my $rec = $statements2->get('exo_fix_new::get_missing_seqreads');
#my $out = Data::Dumper::Dumper($rec);
#warn "$out\n";
$count = scalar(@$rec);
&add_2_mail("---------------------------------------------------------");
&add_2_mail("Found $count missing entries from snp.exoseq_readinfo");
&add_2_mail("---------------------------------------------------------");


# For the update of exoseq_readinfo we need'
#
# Name              
# ------------------
# SEQREAD_NAME         =>   seqread.name
# ID_LOADINGSAMPLE     =>   gel_sample.id_loadingsample
# TEAMNAME             =>   seqread.teamname
# ASP_STATUS           =>   seqread.asp_status
# CM_DATE              =>   seqread.cm_date
# READ_LENGTH          =>   seqread.read_length


my @fix_me;

# Disabled for testing
if ($count > 0){
#if ($count eq 'nada'){


# Go through the list of missing seqreads
    foreach my $next (@$rec){

#	warn "\n";
#	warn "Getting info for ... $next->[0]\n";
	
	my $rec = $statements2->get('exo_fix_new::get_seqread_data', [$next->[0]]);

#	my $out = Data::Dumper::Dumper($rec);
#	warn "$out\n";

	my $hash = {
	    "name" => $rec->[0]->[0],
	    "id_loadingsample" => $rec->[0]->[1],
	    "teamname" => $rec->[0]->[2],
	    "asp_status" => $rec->[0]->[3],
	    "cm_date" => $rec->[0]->[4],
	    "read_length" => $rec->[0]->[5]
	    };

	push @fix_me, $hash;
    }

}


my $check_count = 0;
foreach my $next (@fix_me){
    $check_count++;
    &add_2_mail("$check_count\tMaking new entry for $next->{name}");
    eval {

	&add_2_mail("insert into exoseq_readinfo\n(SEQREAD_NAME, ID_LOADINGSAMPLE, TEAMNAME, ASP_STATUS, CM_DATE, READ_LENGTH)values ($next->{name}, $next->{id_loadingsample}, $next->{teamname}, $next->{asp_status}, $next->{cm_date}, $next->{read_length})");
	
	my $name = $next->{name};
	my $id_loadingsample = $next->{id_loadingsample};
	my $teamname = $next->{teamname};
	my $asp_status = $next->{asp_status};
	my $cm_date = $next->{cm_date};
	my $read_length = $next->{read_length};


	##############################
	# Report mode; DO inactivated
	##############################
	if ($mode eq 'update'){
	    $statements->do('exo_fix_new_snp.sql_lib::make_new_exoseq_readinfo', [$name, $id_loadingsample, $teamname, $asp_status, $cm_date, $read_length]);
	}
    };
    if ($@){
	# We hit a problem on the update
	&add_2_mail("$@Error inserting into exoseq_readinfo");
	die "$@Error inserting into exoseq_readinfo\n\n";
    } else {
	
	#####################
	# Commit inactivated
	#####################
	$statements->{DBH}->commit;
	
    }
}


######################
# ... and send a mail
######################
#&send_mail($mail_message);


sub add_2_mail {
    my ($new) = @_;
    my $to_print = $new . "\n"; 
    #print STDOUT "$to_print";
    warn "$to_print";

    $mail_message = $mail_message . "$new\n";
}





sub send_mail {
    my ($message) = @_;
    
    my $email = "dn1, bt1";
    my $subject = "fix_missing_snp_readinfo.pl ran ...";
    my ($mailer);

    eval 
    {
	my $mailer = Mail::Mailer->new("mail");
	
	$mailer->open({ From    => "HelpDesk",
			To      => "$email",
			Subject => "$subject"}) ||  die "Can't open: $!\n";
    
	print $mailer "$message";
	
	close($mailer);
    };

    if ($@){
	print STDERR "Error sending mail; $@\n\nFrom exofix2.pl\nTo $email\nSubject $subject\n\n$message\n";
    }
    
}



##########
# Tidy up
##########
END {

    &send_mail($mail_message);

#    print STDOUT "Rolling back on snp-handle !\n";
    $statements->{DBH}->rollback;
    $statements->end;

#    print STDOUT "Rolling back on cas-handle !";
    $statements2->{DBH}->rollback;
    $statements2->end;
    print STDOUT "Done.\n";
};


