#!/usr/bin/env perl

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 Data::Dumper;

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

my ($camera,			# Camera used
    $telescope,			# Telescope used
    $exp_type,			# Type of exposure
    $path,			# Path to use
    );
GetOptions(
	   'camera|c=s' => \$camera,
	   'telescope|t=s' => \$telescope,
	   'exp_type|e=s' => \$exp_type,
	   'path=s' => \$path,
) or pod2usage( 2 );

pod2usage(
	  -msg => "Required options: --camera --telescope --exp_type --path",
	  -exitval => 3,
	  ) unless scalar @ARGV == 0 or (defined $camera
					 and defined $telescope
					 and defined $exp_type
					 and defined $path);

my $mdcParser = PS::IPP::Metadata::Config->new;	# Metadata config parser

# Look for programs we need
my $missing_tools;
my $pxinject = can_run('pxinject')  or (warn "Can't find pxinject" and $missing_tools = 1);

# Inject new data into the database
if (scalar @ARGV != 0) {
    my @classes;
    my $imfiles;
    if ($camera eq "MEGACAM") {
	for (my $i = 0; $i < 36; $i++) {
	    push @classes, sprintf("ccd%02d", $i);
	}
    } elsif ($camera eq "MCSHORT") {
	@classes = ( 'ccd12', 'ccd13', 'ccd14', 'ccd21', 'ccd22', 'ccd23' );
    } elsif ($camera eq "CTIO_MOSAIC2") {
	@classes = ();
    } else {
	die "Unrecognised camera name: $camera.\n";
    }

    foreach my $exp ( @ARGV ) {
	my $command = "$pxinject -newExp -exp_id $exp -inst $camera -telescope $telescope -exp_type $exp_type -imfiles " . (scalar @classes or 1) ; # Command to run
	my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
	    run( command => $command, verbose => 1 );
	die "Unable to inject $exp: $error_code\n" if not $success;
	
	my @line = split(/\s+/, $$stdout_buf[0]); # The output line, containing the exposure tag
	my $exp_tag = $line[2];	# The exposure tag
	foreach my $class_id (@classes) {
	    my $command = "$pxinject -newImfile -exp_tag $exp_tag -class chip -class_id $class_id -uri $path/$exp.$class_id.fits"; # Command to run
	    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
		run( command => $command, verbose => 1 );
	    die "Unable to inject $exp $class_id: $error_code\n" if not $success;
	}

	if (scalar @classes == 0) {
	    my $command = "$pxinject -newImfile -exp_tag $exp_tag -class fpa -class_id fpa -uri $path/$exp.fits"; # Command to run
	    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
		run( command => $command, verbose => 1 );
	    die "Unable to inject $exp imfile: $error_code\n" if not $success;
	}

    }
}

END {
    my $status = $?;
    system("sync") == 0
        or die "failed to execute sync: $!" ;
    $? = $status;
}


__END__


