#!/usr/bin/env perl

# Copyright (C) 2006  Joshua Hoblitt
#
# $Id: lipp.pl,v 1.1 2006-07-13 01:37:26 jhoblitt Exp $

use strict;
use warnings;

use URI;
use IPC::Cmd qw( can_run run );
use PS::IPP::Metadata::Config;

# look for commands we need
my $missing_tools;
my $p0tool = can_run('p0search')
    or (warn "can't find p0search" and $missing_tools = 1);
my $p2tool = can_run('p2search')
    or (warn "can't find p2search" and $missing_tools = 1);
my $ppimage = can_run('ppImage')
    or (warn "can't find ppImage" and $missing_tools = 1);

die "can't continue with missing pXtools" if $missing_tools;

delete $ENV{'PS_ALLOC_CHECK'};

# look for new exposures
my $buffer;
my( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
    run(command => "$p0tool -pending", verbose => 0);

if (not $success) {
    die "p0search failed";
}

our $mdcparser = PS::IPP::Metadata::Config->new;
our $p0state;
our $p2state;

updatep0state();
updatep2state();
processp2queue();

use Data::Dumper;
#print Dumper($p0state);
#print Dumper($p2state);

sub processp2queue
{
    foreach my $task (@$p2state) {
        dop2($task->uri);
    }
}

sub dop2
{
    my $url = shift;

    warn "dop2: $url\n";

    my $uri = URI->new($url);
    my $path = $uri->path;
    my $output = $path;
    $output =~ s/\.[^\.]+$//;

# ppImage -recipe PHASE2 p2all.config -bias bias.fits -flat flat.fits 
# -file 810527f.fits o_foo
    my( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
   run(command => "ppImage -recipe PHASE2 p2all.config -bias bias.fits -flat flat.fits -file $path $output");

    if (not $success) {
        unlink("$output.fit");
        die "ppImage failed";
    }

    return 1;
}

sub updatep0state
{
    my $buffer;
    my( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
        run(command => "$p0tool -pending", verbose => 0);

    if (not $success) {
        die "p0search failed";
    }

    my $p0parse = $mdcparser->parse(join "", @$stdout_buf);
    $p0state = p0parse2state($p0parse);

    return 1;
}

sub updatep2state
{
    my $buffer;
    my( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
        run(command => "$p2tool -pending", verbose => 0);

    if (not $success) {
        die "p2search failed";
    }

    my $p2parse = $mdcparser->parse(join "", @$stdout_buf);
    $p2state = p2parse2state($p2parse);

    return 1;
}

sub p0parse2state
{
    my $parse = shift;

    my @state;
    foreach my $md (@$parse) {
        my $values = values2hash($md->{value});
        push @state, $values;
    }

    return \@state;
}

sub p2parse2state
{
    my $parse = shift;

    my @state;
    foreach my $md (@$parse) {
        my $values = values2hash($md->{value});
        push @state, $values;
    }

    return \@state;
}

sub values2hash
{
    my $values = shift;

    my %hash;
    foreach my $data (@$values) {
        $hash{$data->{name}} = $data->{value};
    }

    return \%hash;
}
