#!/usr/bin/env perl

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

my ($db_host, $db_name, $db_user, $db_pw); # Database details
my ($stack_id);                 # Stack 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
           'stack_id=s' => \$stack_id, # Stack identifier
    ) or die "Unable to parse arguments.\n";
die "Unknown option: @ARGV\n" if @ARGV;
die "Required options: --dbhost --dbname --dbuser --dbpass --stack_id\n"
    unless defined $db_host
    and defined $db_name
    and defined $db_user
    and defined $db_pw
    and defined $stack_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" .
    " FROM stackRun" .
    " JOIN stackInputSkyfile USING(stack_id)" .
    " JOIN warpSkyfile USING(warp_id, skycell_id)" .
    " WHERE stack_id = $stack_id";

# List of warps
my $warps = $db->selectcol_arrayref( $sql,
                                     { Columns => [1] }
                                     ) or die "Unable to execute SQL: $DBI::errstr";

$sql = "SELECT path_base FROM stackSumSkyfile WHERE stack_id = $stack_id";

# List of stacks
my $stacks = $db->selectcol_arrayref( $sql,
                                     { Columns => [1] }
                                     ) or die "Unable to execute SQL: $DBI::errstr";

$db->disconnect;




foreach my $stack_path ( @$stacks ) {
    print "$stack_path\n";
    #make jpg of unconv
    my @ext = (".fits", ".unconv.fits",".exp.fits", ".unconv.exp.fits" );
  #  if ($db_name == "isp") {
#	#add in other single chip stuff if needed
#	@ext = (".exp.fits", ".unconv.exp.fits");
#    } 
  
    
    #make jpg of conv
    foreach my $stuff (@ext) {
	my $file = $stack_path.$stuff;
	print "$file\n";
	`echo $file > list`;
	my $base = $file;
	$base =~ s/.fits//;
	$base =~ s/.*\///g;
	print $base;
	`ppSkycell -images list $base`;
    }


}



foreach my $warp_path ( @$warps ) {
    print "$warp_path\n";
    my @ext = (".fits");
     foreach my $stuff (@ext) {
	my $file = $warp_path.$stuff;
	print "$file\n";
	`echo $file > list`;
	my $base = $file;
	$base =~ s/.fits//;
	$base =~ s/.*\///g;
	print $base;
	`ppSkycell -images list $base`;
    }
   


}
