#!/bin/env perl

# Check whether a fits file can be unpacked successfully

use strict;
use warnings;
#use PS::IPP::Metadata::Config;
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 File::Basename;
use File::Temp qw(tempfile);
use Carp;

use IPC::Cmd qw( can_run run );

my ($filename, $verbose, $output);

GetOptions(
    'verbose|v'      => \$verbose, 
    'output|o=s'     => \$output,
) or pod2usage( 2 );

pod2usage( -msg => "uri is required", -exitval => 2 )
    if !@ARGV;

my $ipprc =  PS::IPP::Config->new();

my $file = shift;

my $scheme = file_scheme($file);

my $resolved;
if ($scheme and $scheme = 'neb') {
    $resolved = $ipprc->file_resolve($file);
    die "failed to resolve $file\n" if !$resolved;
} else {
    $resolved = $file;
}

if (!-e $resolved) {
    die "$file not found\n";
}


my $tempfile;
if (!$output) {
    ($tempfile, $output) = tempfile("/tmp/checkfits.XXXX", UNLINK => 1);
}

my $funpack = can_run('funpack') or die "can't find funpack\n";

my $command = "$funpack -S $resolved > $output";

my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
        run(command => $command, verbose => $verbose);
if (!$success) {
    my $exit_status = $error_code >> 8;
    warn ("funpack of $resolved failed with exit status $exit_status.\n") if $verbose;
    warn ("$resolved is corrupt.\n");
    exit $exit_status;
}

print "$file unpack successful.\n" if $verbose;


exit 0;

__END__

=pod

=head1 NAME

checkfits - see whether a fits file can be successfully decompressesd

=head1 SYNOPSIS
    
    checkfits <uri> [--output <file>] [--verbose]


=over 4


=item * <uri> 

Uri of file to be checked.  (URI may be a nebulous path).

=item * --output <file>

Save the unpacked fits to <file>.

=item * --verbose

Causes checkfits to be chatty.


=cut
