#!/usr/bin/perl
use strict;
use warnings;
my($app_svnid) = '$HeadURL$ $LastChangedRevision$'; ## no critic (RequireInterpolationOfMetachars)
use lib substr(`ade-config ade_share_prefix`,0,-1) . '/include'; ## no critic (ProhibitBacktickOperators)
use ADE;
use lib substr(`fad-config fad_share_prefix`,0,-1) . '/include'; ## no critic (ProhibitBacktickOperators)
use FAD;
use Getopt::Long qw(:config no_ignore_case);
use Fatal qw( close unlink );  #  obviate checking close()'s return code

my(%fadcat_defined_errors) = (
    fadcat_err_access        => { fmt => '%s: can\'t %s' },
);

#   Options
my($opt_regexp, $opt_outfile);

sub fadcat
{
    my($errstack_ref) = @_;
    my($rc, $out_handle, %data_store);

    #  Set ADE options
    ADE::ade_err_registerdefderrs(\%fadcat_defined_errors);

    #  Defaults for options
    $opt_regexp  = undef;
    $opt_outfile = undef;

    #  Register options
    if (($rc=ADE::ade_opt_register($errstack_ref, 'g:so:s', 'grep:s,file:s', 'main::fadcat_opt_handler_%s')) != $ADE::ADE_ERR_OK) {
        return($rc);
    }

    #  Register handler functions
    if (($rc=ADE::ade_msg_register($errstack_ref, \&fadcat_usage, \&fadcat_version, \&fadcat_listpaths)) != $ADE::ADE_ERR_OK) {
        return($rc);
    }

    #  Process options
    ADE::ade_err_debug($errstack_ref, 10, 'fadcat: processing options ...');
    if (($rc=ADE::ade_opt_process($errstack_ref)) != $ADE::ADE_ERR_OK) {
        return($rc);
    }

    #  Process arguments
    #  All arguments are optional.

    #  Guts
    if (defined $ARGV[0]) {
        while (defined $ARGV[0]) {
            $_ = shift @ARGV;
            ADE::ade_err_debug($errstack_ref, 5, "fadcat: calling ade_fcm_openreadcompressed() to open $_ ...");
            if (($rc=ADE::ade_fcm_openreadcompressed($errstack_ref, $_, \*IN_HANDLE)) != $ADE::ADE_ERR_OK) {
                 ADE::ade_err_error($errstack_ref, 'fadcat_err_access', $_, 'open');
                 return($rc);
            }
            ADE::ade_err_debug($errstack_ref, 5, 'fadcat: calling fad_load() ...');
            if (($rc=FAD::fad_load($errstack_ref, \*IN_HANDLE, \%data_store, undef, $opt_regexp)) != $ADE::ADE_ERR_OK) {
                return($rc);
            }
            ADE::ade_err_debug($errstack_ref, 5, 'fadcat: fad_load() returned');
            close IN_HANDLE;
        }
    } else {
        ADE::ade_err_debug($errstack_ref, 5, 'fadcat: calling fad_load() ...');
        if (($rc=FAD::fad_load($errstack_ref, \*STDIN, \%data_store, undef, $opt_regexp)) != $ADE::ADE_ERR_OK) {
            return($rc);
        }
        ADE::ade_err_debug($errstack_ref, 5, 'fadcat: fad_load() returned');
    }

    if (defined $opt_outfile) {
        ADE::ade_err_debug($errstack_ref, 10, 'fadcat: opening output file ...');
        ADE::ade_tmp_registerfile($errstack_ref, $opt_outfile);
        if (($rc=ADE::ade_fcm_openwritecompressed($errstack_ref, $opt_outfile, \*OUT_HANDLE)) != $ADE::ADE_ERR_OK) {
            ADE::ade_err_error($errstack_ref, 'fadcat_err_access', $opt_outfile, 'open');
            return($rc);
        }
        $out_handle = \*OUT_HANDLE;
    } else {
        $out_handle = \*STDOUT;
    }

    ADE::ade_err_debug($errstack_ref, 10, 'fadcat: dumping FAD store to ' . (defined $opt_outfile ? $opt_outfile : 'stdout') .  ' ...');
    if (($rc=FAD::fad_dump($errstack_ref, $out_handle, \%data_store)) != $ADE::ADE_ERR_OK) {
        return($rc);
    }

    if (defined $opt_outfile) {
        close OUT_HANDLE;
        ADE::ade_tmp_deregisterfile($errstack_ref, $opt_outfile);
    }

    #  Ensure sensible return code
    return($ADE::ADE_ERR_OK);
}

sub fadcat_opt_handler_g ## no critic (RequireArgUnpacking)
{
    return(fadcat_opt_handler_grep(@_));
}

sub fadcat_opt_handler_o ## no critic (RequireArgUnpacking)
{
    return(fadcat_opt_handler_file(@_));
}

sub fadcat_opt_handler_grep
{
    my($errstack_ref, $regexp) = @_;

    $opt_regexp = $regexp;

    return($ADE::ADE_ERR_OK);
}

sub fadcat_opt_handler_file
{
    my($errstack_ref, $outfile) = @_;

    $opt_outfile = $outfile;

    return($ADE::ADE_ERR_OK);
}

sub fadcat_version
{
    my($errstack_ref, $version_text_ref) = @_;

    return(ADE::ade_smf_extractversionfromsvnstring($errstack_ref, $app_svnid, $version_text_ref));
}

sub fadcat_listpaths
{
    my($errstack_ref, $pathlist_text_ref) = @_;
    my($rc);

    ${$pathlist_text_ref} = undef;

    return($ADE::ADE_ERR_OK);
}

sub fadcat_usage
{
    my($errstack_ref, $usage_text_ref, $passno) = @_;

    if ($passno == 1) {
        ${$usage_text_ref} = '[ <file> ... ]';
    } elsif ($passno == 2) {
        ${$usage_text_ref} = "         -g        | --grep=<regexp>         grep out lines containing <regexp>\n" .
                             "         -o        | --file=<outfile>        send output to <outfile>\n";
    }

    return($ADE::ADE_ERR_OK);
}

ADE::ade_gep_main(\&fadcat);
