#!/usr/bin/env perl

# this program injects a list of single-file exposures into the db, taking the
# filename (without .fits) as the exp_tag.

use warnings;
use strict;

use IPC::Cmd qw( can_run run );
use PS::IPP::Metadata::Config;
use PS::IPP::Metadata::List qw( parse_md_list );
use File::Spec;
use File::Find::Rule;
use PS::IPP::Config;
my $ipprc = PS::IPP::Config->new();
my $mdcParser = PS::IPP::Metadata::Config->new;	# Parser for metadata config files

use Getopt::Long qw( GetOptions :config auto_help auto_version gnu_getopt );
use Pod::Usage qw( pod2usage );

# Parse the command-line arguments
my ($workdir, $dbname);
GetOptions(
    'workdir|w=s'   => \$workdir,  # working directory for output files
    'dbname|d=s'    => \$dbname    # Database name
) or pod2usage( 2 );

pod2usage( -msg => "Usage: $0 [--workdir path] [--dbname dbname] (files)", -exitval => 2 ) if scalar @ARGV == 0;

my $pxinject = can_run('pxinject') or die "Can't find pxinject\n";
my $ppStats = can_run('ppStats') or die "Can't find ppStats\n";

# if workdir is not defined, assign the current path
# XXX we need to handle relative paths for workdir (not allowed)
if (! $workdir) {
    $workdir = File::Spec->rel2abs( "." );
}

my $num = 0;
foreach my $file ( @ARGV ) {
    my $absfile = File::Spec->rel2abs( $file );
    inject($absfile, $workdir, $dbname);
    $num ++;
}

print "$num files injected.\n";

sub inject
{
    my $absfile = shift;		# absolute path for this file
    my $workdir  = shift;		# absolute path for output directory
    my $dbname = shift;

    my ( $vol, $path, $name ) = File::Spec->splitpath( $absfile );
    my ( $exp ) = $name =~ /(.*)\.fits/;

    my $relfile = $ipprc->convert_filename_relative( $absfile );

    my $command_type = "$ppStats -concept FPA.OBSTYPE -concept FPA.TELESCOPE -concept FPA.INSTRUMENT $absfile";
    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) = run(command => $command_type, verbose => 1);
    die "Unable to perform ppStats: $error_code\n" if not $success;
    my $metadata = $mdcParser->parse(join "", @$stdout_buf) 
        or die "unable to parse metadata config doc";

    my $type;
    my $telescope;
    my $instrument;
    foreach my $row (@$metadata) {
	if ($row->{name} eq "FPA.TELESCOPE")  { $telescope = $row->{value}; }
	if ($row->{name} eq "FPA.INSTRUMENT") { $instrument = $row->{value}; } # this entry must return the camera in the ipp/config system which we load
#	if ($row->{name} eq "FPA.OBSTYPE")    { $type = $row->{value}; }
    }
    
    my $command_exp = "$pxinject -newExp -exp_id $exp -inst $instrument -telescope $telescope -imfiles 1 -workdir $workdir" ; # Command to run
    if ($dbname) {
	$command_exp = "$command_exp -dbname $dbname";
    }

    my ( $success_exp, $error_code_exp, $full_buf_exp, $stdout_buf_exp, $stderr_buf_exp ) =
	run( command => $command_exp, verbose => 1 );
    die "Unable to inject $exp: $error_code_exp\n" if not $success_exp;
    
    my @line = split(/\s+/, $$stdout_buf_exp[0]); # The output line, containing the exposure tag
    my $exp_tag = $line[2];	# The exposure tag
    
    my $command_imfile = "$pxinject -newImfile -exp_tag $exp_tag -class fpa -class_id fpa -uri $relfile"; # Command to run
    if ($dbname) {
	$command_imfile = "$command_imfile -dbname $dbname";
    }
    
    my ( $success_imfile, $error_code_imfile, $full_buf_imfile, $stdout_buf_imfile, $stderr_buf_imfile ) = run( command => $command_imfile, verbose => 1 );
    die "Unable to inject $exp imfile: $error_code_imfile\n" if not $success_imfile;

    return 1;
}


__END__
