#!/usr/bin/env perl

#
# Copy chip outputs 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 EXTENSIONS => { 'IMAGE' => '.ch.fits', # Image
                             'MASK' => '.ch.mk.fits', # Mask
                             'WEIGHT' => '.ch.wt.fits', # Weight
                             'SOURCES' => '.cmf', # Sources
                         };

my ($db_host, $db_name, $db_user, $db_pw); # Database details
my ($chip_id, $class_id);       # Chip of interest
my ($input);                    # Input list
my ($products);                 # Products of interest

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
           'chip_id=s' => \$chip_id, # Chip identifier
           'class_id=s' => \$class_id, # Class identifier
           'products=s' => \$products, # Products of interest
           ) or die "Unable to parse arguments.\n";
die "Unknown option: @ARGV\n" if @ARGV;
die "Required options: --dbhost --dbname --dbuser --dbpass --chip_id\n"
    unless defined $db_host
    and defined $db_name
    and defined $db_user
    and defined $db_pw
    and defined $chip_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 path_base, class_id" .
    " FROM chipProcessedImfile " .
    " WHERE chip_id = $chip_id";
$sql .= " AND class_id = \'$class_id\'" if defined $class_id;

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

my @products;                   # Array of products
if (defined $products) {
    @products = split /,/, $products;
} else {
    @products = keys %{EXTENSIONS()};
}

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

    my $name = "$path.$class_id"; # Full name
    foreach my $product ( @products ) {
        copy_extension( $name, ${EXTENSIONS()}{$product} );
    }
}

# Pau.


sub copy_extension
{
    my $path = shift;           # Path to copy
    my $ext = shift;            # Extension to copy

    my $neb = "$path$ext"; # Nebulous file
    my $source = `neb-locate --path $neb` or die "Unable to locate $neb\n"; # Actual file
    chomp $source;
    my ($target) = $source =~ m|^.*:(.*)|; # Target name
    !system "cp $source $target" or die "Unable to copy $source\n";
}
