#!/usr/bin/env perl

#
# Copy warp 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 IMAGE => '.ch.fits';  # Image extension
use constant MASK => '.ch.mk.fits'; # Mask extension
use constant WEIGHT => '.ch.wt.fits'; # Weight extension
use constant ASTROM => '.smf';  # Astrometry extension



my ($db_host, $db_name, $db_user, $db_pw); # Database details
my ($warp_id);                  # Warp of interest
my ($skycell_id);               # Skycell of interest
my ($image, $mask, $weight); # Files to contain input lists

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
           'warp_id=s' => \$warp_id, # Warp identifier
           'skycell_id=s' => \$skycell_id, # Skycell identifier
           'image=s' => \$image, # File with images
           'mask=s' => \$mask,  # File with masks
           'weight=s' => \$weight, # File with weights
           ) or die "Unable to parse arguments.\n";
die "Unknown option: @ARGV\n" if @ARGV;
die "Required options: --dbhost --dbname --dbuser --dbpass --warp_id\n"
    unless defined $db_host
    and defined $db_name
    and defined $db_user
    and defined $db_pw
    and defined $warp_id
    and defined $skycell_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 AS chip_path_base," .
    " class_id," .
    " camProcessedExp.path_base AS cam_path_base" .
    " FROM warpRun" .
    " JOIN warpSkyCellMap USING(warp_id)" .
    " JOIN fakeRun USING(fake_id)" .
    " JOIN camRun USING(cam_id)" .
    " JOIN camProcessedExp USING(cam_id)" .
    " JOIN chipProcessedImfile USING(chip_id, class_id)" .
    " WHERE warp_id = $warp_id" .
    " AND skycell_id = \'$skycell_id\'";


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

my ($imageList, $maskList, $weightList); # Files to write to
open $imageList, "> $image" if defined $image;
open $maskList, "> $mask" if defined $mask;
open $weightList, "> $weight" if defined $weight;

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

    $chip .= '.' . $class_id;

    my $imageName = $chip . IMAGE(); # Name of image
    my $maskName = $chip . MASK(); # Name of mask
    my $weightName = $chip . WEIGHT(); # Name of weight
    my $astromName = $cam . ASTROM(); # Name of astrometry

    print $imageList "$imageName\n" if defined $image;
    print $maskList "$maskName\n" if defined $mask;
    print $weightList "$weightName\n" if defined $weight;

    copy_file( $imageName );
    copy_file( $maskName );
    copy_file( $weightName );
    copy_file( $astromName );
}

close $imageList if defined $image;
close $maskList if defined $mask;
close $weightList if defined $weight;


# Pau.


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

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