#!/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 );

use constant SOURCES => '.cmf';  # Sources extension
use constant MASK => '.ch.mk.fits';  # Mask extension


my ($db_host, $db_name, $db_user, $db_pw); # Database details
my ($cam_id);                              # Camera run of interest
my ($sources, $masks);                     # Name for list files
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
           'sources=s' => \$sources, # File with sources
           'masks=s' => \$masks, # File with masks
           '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";

# Query to run
my $sql = "SELECT" .
    " chipProcessedImfile.path_base," .
    " class_id" .
    " FROM camRun" .
    " JOIN chipProcessedImfile USING(chip_id)" .
    " WHERE cam_id = $cam_id";

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

my ($sourcesList, $masksList); # Files to write to
open $sourcesList, "> $sources" if defined $sources;
open $masksList, "> $masks" if defined $masks;

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

    $path .= '.' . $class_id;

    my $sourcesName = $path . SOURCES(); # Name of sources file
    my $maskName = $path . MASK(); # Name of mask file

    $sourcesName = copy_file( $sourcesName );
    $maskName = copy_file( $maskName );

    print $sourcesList "$sourcesName\n" if defined $sources;
    print $masksList "$maskName\n" if defined $masks;
}

close $sourcesList if defined $sources;
close $masksList if defined $masks;


# 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;
}
