#!/usr/bin/perl -w
use DBI;
use constant DB_SOCKET => '/var/run/mysqld/mysqld.sock'; # Socket for mysql


my $dbname = 'gpc1';
my $dbserver = 'ippdb01';
my $dbuser = 'ippuser';
my $dbpass = 'ippuser';

my %OSS_orig= ();
my %OSS_reprocessed = ();


my $db = DBI->connect(
   "DBI:mysql:database=${dbname};host=${dbserver};mysql_socket=" .
   DB_SOCKET(),${dbuser},${dbpass}, 
   { RaiseError => 1, AutoCommit => 1}
   ) or die "Unable to connect to database $DBI::errstr\n";

my $qdiffs = "select distinct(warp1), warp2 from diffRun join diffInputSkyfile using (diff_id) where data_group = 'OSS.20101012' or data_group = 'OSS.20101011';";

my $qosswarpsorig = "SELECT rawExp.exp_id,warpRun.warp_id FROM   warpRun, fakeRun, camRun, chipRun, rawExp WHERE warpRun.fake_id = fakeRun.fake_id AND fakeRun.cam_id = camRun.cam_id AND camRun.chip_id = chipRun.chip_id AND chipRun.exp_id = rawExp.exp_id and (chipRun.data_group = 'OSS.20101012' or chipRun.data_group = 'OSS.20101011') ;";

my $qosswarpsrep = "SELECT rawExp.exp_id,warpRun.warp_id FROM   warpRun, fakeRun, camRun, chipRun, rawExp WHERE warpRun.fake_id = fakeRun.fake_id AND fakeRun.cam_id = camRun.cam_id AND camRun.chip_id = chipRun.chip_id AND chipRun.exp_id = rawExp.exp_id and (chipRun.data_group = 'MopsTest.20100708') ;";

$diffs = $db->selectall_arrayref( $qdiffs ) ||
        die "Unable to execute SQL: $DBI::errstr\n";
$osswarpsorig = $db->selectall_arrayref( $qosswarpsorig ) ||
        die "Unable to execute SQL: $DBI::errstr\n";
$osswarpsrep = $db->selectall_arrayref( $qosswarpsrep ) ||
        die "Unable to execute SQL: $DBI::errstr\n";

$db->disconnect();


foreach $it (@{$osswarpsorig}) {
   
    $OSS_orig{${$it}[1] } = ${$it}[0];   #oss orig will sort by warps -> exp_id

}

foreach $it (@{$osswarpsrep}) {
   
    $OSS_reprocessed{${$it}[0] } = ${$it}[1];   #oss rep will sort by exp_id -> warps

}

$total =0;

foreach $it (@{$diffs}) {
    my ($oldexp1, $newwarp1, $oldexp2, $newwarp2);

    $oldexp1= $OSS_orig{${$it}[0]};
    $newwarp1= $OSS_reprocessed{$oldexp1};

    $oldexp2= $OSS_orig{${$it}[1]};
    $newwarp2= $OSS_reprocessed{$oldexp2};

  #  print "${$it}[0] ${$it}[1] $oldexp1 $oldexp2 $newwarp1 $newwarp2 \n";

    print "difftool -definewarpwarp -exp_id $oldexp2 -template_exp_id $oldexp1 -input_label MopsTest.20100708 -template_label MopsTest.20100708 -timediff 3600 -set_label MopsTest.20100708 -pretend -dbname gpc1 -set_workdir neb://\@HOST\@.0/gpc1/MopsTest.20100708 -simple";
    print "\n";
    $count = `difftool -definewarpwarp -exp_id $oldexp2 -template_exp_id $oldexp1 -input_label MopsTest.20100708 -template_label MopsTest.20100708 -timediff 3600 -set_label MopsTest.20100708 -dbname gpc1 -set_workdir neb://\@HOST\@.0/gpc1/MopsTest.20100708 -simple | wc -l`;
    chomp $count;

    $total = $count+$total;
}


print $total;
