#!/usr/bin/env perl

#
# Copy diff 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 );

# Filename extensions for warps
use constant WARP_EXTENSIONS => { 'IMAGE' => '.fits', # Image
                                  'MASK' => '.mask.fits', # Mask
                                  'WEIGHT' => '.wt.fits', # Weight
                                  'SOURCES' => '.cmf', # Sources
                              };
# Filename extensions for stacks
use constant STACK_EXTENSIONS => { 'IMAGE' => '.fits', # Image
                                   'MASK' => '.mask.fits', # Mask
                                   'WEIGHT' => '.wt.fits', # Weight
                                   'SOURCES' => '.cmf', # Sources
                               };

my ($db_host, $db_name, $db_user, $db_pw); # Database details
my ($diff_id, $skycell_id);     # Diff and skycell of interest
my ($input);                    # Input list

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
           'diff_id=s' => \$diff_id, # Diff identifier
           'skycell_id=s' => \$skycell_id, # Skycell identifier
           'input=s'  => \$input, # Input list to generate
           ) or die "Unable to parse arguments.\n";
die "Unknown option: @ARGV\n" if @ARGV;
die "Required options: --dbhost --dbname --dbuser --dbpass --diff_id\n"
    unless defined $db_host
    and defined $db_name
    and defined $db_user
    and defined $db_pw
    and defined $diff_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" .
    "     warpSkyfile.path_base AS warp_path_base," .
    "     NULL AS stack_path_base" .
    " FROM diffRun" .
    " JOIN diffInputSkyfile USING(diff_id)" .
    " JOIN warpSkyfile" .
    "     ON warpSkyfile.skycell_id = diffInputSkyfile.skycell_id" .
    "     AND (warpSkyfile.warp_id = diffInputSkyfile.warp1" .
    "         OR warpSkyfile.warp_id = diffInputSkyfile.warp2)" .
    " WHERE diff_id = $diff_id";
$sql .= " AND diffInputSkyfile.skycell_id = \'$skycell_id\'" if defined $skycell_id;
$sql .= " UNION" .
    " SELECT" .
    "     NULL AS warp_path_base," .
    "     stackSumSkyfile.path_base AS stack_path_base" .
    " FROM diffRun" .
    " JOIN diffInputSkyfile USING(diff_id)" .
    " JOIN stackSumSkyfile" .
    "     ON (stackSumSkyfile.stack_id = diffInputSkyfile.stack1" .
    "         OR stackSumSkyfile.stack_id = diffInputSkyfile.stack2)" .
    " WHERE diff_id = $diff_id";
$sql .= " AND diffInputSkyfile.skycell_id = \'$skycell_id\'" if defined $skycell_id;


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

foreach my $row ( @$results ) {
    my $warp = $$row[0];        # Warp path
    my $stack = $$row[1];       # Stack path

    if (defined $warp) {
        copy_extensions( $warp, WARP_EXTENSIONS() );
    } elsif (defined $stack) {
        copy_extensions( $stack, STACK_EXTENSIONS() );
    }
}


# Pau.


sub copy_extensions
{
    my $path = shift;           # Path to copy
    my $extensions = shift;     # Extensions structure

    foreach my $type ( keys %$extensions ) {
        my $ext = $$extensions{$type}; # Extension
        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";
    }
}
