#!/usr/bin/env perl

#
# Copy camera stage inputs to the current directory
#

use warnings;
use strict;

use DBI;
use constant DB_SOCKET => '/var/run/mysqld/mysqld.sock'; # Socket for mysql
use Getopt::Long qw( GetOptions :config auto_help auto_version gnu_getopt );


my ($db_host, $db_name, $db_user, $db_pw); # Database details
my ($cam_id);                              # Camera run of interest
my ($muggle);                   # No magicked inputs?

GetOptions(
           'dbhost=s' => \$db_host, # Database host name
           'dbname=s' => \$db_name, # Database name
           'dbuser=s' => \$db_user, # Database user
           'dbpass=s' => \$db_pw, # Database p/w
           'cam_id=s' => \$cam_id, # Camera run identifier
           'muggle'   => \$muggle, # No magicked inputs?
           ) or die "Unable to parse arguments.\n";
die "Unknown option: @ARGV\n" if @ARGV;
die "Required options: --dbhost --dbname --dbuser --dbpass --cam_id\n"
    unless defined $db_host
    and defined $db_name
    and defined $db_user
    and defined $db_pw
    and defined $cam_id;

# Database connection
my $db = DBI->connect( "DBI:mysql:database=$db_name;host=$db_host;mysql_socket=" . DB_SOCKET(),
                       $db_user,
                       $db_pw,
                       { RaiseError => 1, AutoCommit => 1 }
                       ) or die "Unable to connect to database: $DBI::errstr";

my $path;                       # Path for camera-level products
{
    # Query to run
    my $sql = "SELECT" .
        " path_base" .
        " FROM camProcessedExp" .
        " WHERE cam_id = $cam_id";

    my $results = $db->selectall_arrayref( $sql ) or die "Unable to execute SQL: $DBI::errstr";

    my $row = $$results[0];
    $path = $$row[0];
}

copy_file("$path.smf");


my $sql = "SELECT" .
    " class_id" .
    " FROM camRun JOIN chipProcessedImfile USING(chip_id)" .
    " WHERE cam_id = $cam_id AND quality = 0";

my $results = $db->selectall_arrayref( $sql ) or die "Unable to execute SQL: $DBI::errstr";
$db->disconnect;

foreach my $row ( @$results ) {
    my $class_id = $$row[0];    # Class identifier

    copy_file("$path.$class_id.mk.fits");
}


# Pau.


sub copy_file
{
    my $file = shift;           # File to copy

    if (defined $muggle) {
        my @file = split /\//, $file;
        my $last = pop @file;
        push @file, "SR_$last";
        $file = join '/', @file;
    }

    my $source = `ipp_datapath.pl $file` or die "Unable to locate $file\n"; # Actual file
    chomp $source;
    my ($target) = $source =~ m|^.*[:/](.*)|; # Target name
    !system "cp $source $target" or die "Unable to copy $source\n";
    return $target;
}
