#! /usr/bin/env perl

use Carp;
use warnings;
use strict;
use IPC::Cmd 0.36 qw( can_run run );
use PS::IPP::Metadata::List qw( parse_md_list );
use PS::IPP::Config 1.01 qw( :standard );
use Getopt::Long qw( GetOptions :config auto_help auto_version gnu_getopt );
use Pod::Usage qw( pod2usage );
use DBI;

my $dbname = 'hsc';
my $dbhost = 'hsc00';
my $ipprc  = PS::IPP::Config->new();
my $siteConfig = $ipprc->{_siteConfig};


my $db = init_hsc_db();
my %registered_exp = ();

get_registered_exp_names();

my $directory = shift(@ARGV);

my @fits = <$directory/*.fits>;
foreach my $f (@fits) {
    if ($f !~ /00.fits/) { next; }

    my $exp_name = $f;
    $exp_name =~ s/.fz$//;
    $exp_name =~ s/.fits$//;
    $exp_name =~ s%.*/%%;

    my $base = $exp_name;
    $base =~ s/^HSCA//;
    $base =~ s/00$//;

    if (($base % 2) != 0) { next; }
    if (exists($registered_exp{$exp_name})) { next; }
#    print "# $exp_name\n";
    my $set1 = "${directory}/HSCA${base}??.fits";
    $base =~ s/2$/3/;
    $base =~ s/4$/5/;
    $base =~ s/6$/7/;
    $base =~ s/8$/9/;
    $base =~ s/0$/1/;
    my $set2 = "${directory}/HSCA${base}??.fits";

    my @check_1 = <"$set1">;
    my @check_2 = <"$set2">;

    my $count = scalar(@check_1) + scalar(@check_2);

    if ($count == 112) {
	print "ipp_inject_fileset.pl --workdir ${directory}/regdata --dbname hsc --telescope subaru --camera hsc $set1 $set2\n";
    }
    else {
	print "echo 'exp_name HSCA${base} does not have the correct count of image files ($count).'\n";
    }
}

sub get_registered_exp_names {
    my $query = 'select exp_name from rawExp';
    my $r = $db->selectall_arrayref( $query );
    
    foreach my $rr (@{ $r }) {
	my ($exp_name) = @{ $rr };
	$registered_exp{$exp_name} = 1;
    }
}

sub init_hsc_db {
    ## change to use the siteConfig setting, while readonly probably do not want to use a readonly replicated DB incase it gets behind
    my $dbserver = $dbhost;
    my $dbuser = metadataLookupStr($ipprc->{_siteConfig}, "RO_DBUSER");
    my $dbpass = metadataLookupStr($ipprc->{_siteConfig}, "RO_DBPASSWORD");
    die "database configuration not set up" unless defined($dbserver);
    die "database configuration not set up" unless defined($dbuser);
    die "database configuration not set up" unless defined($dbpass);
    use constant DB_SOCKET => '/var/run/mysqld/mysqld.sock';
    $db = DBI->connect("DBI:mysql:database=${dbname};host=${dbserver};" .
                       "mysql_socket=" . DB_SOCKET(),
                       ${dbuser},${dbpass},
{ RaiseError => 1, AutoCommit => 1}
        ) or die "Unable to connect to database $DBI::errstr\n";
return($db);
}

