#!/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 VARIANCE => '.ch.wt.fits'; # Variance 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, $variance); # Files to contain input lists
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
           '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
           'variance=s' => \$variance, # File with variances
           '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 --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, $varianceList); # Files to write to
open $imageList, "> $image" if defined $image;
open $maskList, "> $mask" if defined $mask;
open $varianceList, "> $variance" if defined $variance;

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 $varianceName = $chip . VARIANCE(); # Name of variance
    my $astromName = $cam . ASTROM(); # Name of astrometry

    print $imageList "$imageName\n" if defined $image;
    print $maskList "$maskName\n" if defined $mask;
    print $varianceList "$varianceName\n" if defined $variance;

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

close $imageList if defined $image;
close $maskList if defined $mask;
close $varianceList if defined $variance;


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