#!/usr/bin/env perl 

# this script takes a list of exp_names and copies the destreaked smfs to the current directory.
# if given a o____g____o## type of name, it chops off the ## to create a valid exp_name 


use DBI;
use constant DB_SOCKET => '/var/run/mysqld/mysql.sock';

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

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




while (<>) {
    chomp $_;
    $exp_name = $_;
    $exp_name=~s/\d\d$//;
    print $exp_name;
    my $qy = "select exp_name, chipRun.state, camRun.state, path_base  from rawExp left join chipRun using (exp_id) left join camRun using (chip_id) left join camProcessedExp using (cam_id)  where exp_name = '$exp_name';";
    my $query = $db->selectall_arrayref($qy) || 
    die "Unable to execute SQL: $DBI::errstr\n";

    foreach my $item (@{$query}) {
	print "${$item}[0]xx${$item}[3]yy\n";
    $path=  ${$item}[3];
	


    chomp $path;
	$name = $path . '.smf';

	$path =~ s/o\d+g\d+o\.\d+\.cm\.\d+$//;
	print "$path\n";
	$count = `neb-ls $path | grep smf | wc -l`;
	    if ($count == 2) {
		print "good to copy\n";
		$nebpath= `neb-locate --path $name`;
		chomp $nebpath;
		print "cp $nebpath $exp_name.smf\n";
		`cp $nebpath $exp_name.smf`;
	}


    }

}
