#!/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 ($dbname,			# Database name to use
    $workdir,			# Working directory
    $no_op,			# No operations?
    $no_update,			# No updating?
    );
GetOptions(
	   'dbname|d=s' => \$dbname,
	   'workdir|w=s' => \$workdir,
	   'no-op' => \$no_op,
	   'no-update' => \$no_update,
) or pod2usage( 2 );

pod2usage(
	  -msg => "Required options: --dbname",
	  -exitval => 3,
	  ) unless defined $dbname;

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

# Look for programs we need
my $missing_tools;
my $chiptool = can_run('chiptool') or (warn "Can't find chiptool" and $missing_tools = 1);
my $chip = can_run('chip_imfile.pl') or (warn "Can't find chip_imfile.pl" and $missing_tools = 1);
die "Can't find required tools.\n" if $missing_tools;

# Phase 2 imfile processing
my $list;
{
    my $command = "$chiptool -pendingimfile -dbname $dbname"; # Command to run
    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
	run( command => $command, verbose => 1 );
    die "Unable to get phase 2 imfile list: $error_code\n" if not $success;
    $list = parse_md_list( $mdcParser->parse( join( '', @$stdout_buf ) ) ) or
	die "Unable to parse output from chiptool.\n";
}

foreach my $item (@$list) {
    my $exp_tag = $item->{exp_tag};
    my $camera = $item->{camera};
    my $class_id = $item->{class_id};
    my $uri = $item->{uri};
    
    my $command = "$chip --exp_tag $exp_tag --class_id $class_id --uri $uri --dbname $dbname --camera $camera";
    $command .= " --no-op" if defined $no_op;
    $command .= " --no-update" if defined $no_update;
    $command .= " --workdir $workdir" if defined $workdir;
    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
	run( command => $command, verbose => 1 );
    die "Unable to do phase 2 processing on $exp_tag $class_id: $error_code\n" if not $success;
}

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


__END__


