//
// LDASTools frameCPP - A library implementing the LIGO/Virgo frame
// specification
//
// Copyright (C) 2018 California Institute of Technology
//
// LDASTools frameCPP is free software; you may redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 (GPLv2) of the
// License or at your discretion, any later version.
//
// LDASTools frameCPP is distributed in the hope that it will be useful, but
// without any warranty or even the implied warranty of merchantability
// or fitness for a particular purpose. See the GNU General Public
// License (GPLv2) for more details.
//
// Neither the names of the California Institute of Technology (Caltech),
// The Massachusetts Institute of Technology (M.I.T), The Laser
// Interferometer Gravitational-Wave Observatory (LIGO), nor the names
// of its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// You should have received a copy of the licensing terms for this
// software included in the file LICENSE located in the top-level
// directory of this package. If you did not, you can view a copy at
// http://dcc.ligo.org/M1500244/LICENSE
//

#include <framecpp_config.h>

#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>

#include <iostream>
#include <memory>
#include <stdexcept>

#include "framecpp/Verify.hh"

namespace
{
    enum error_type
    {
        MIN_ERROR = FrameCPP::Verify::MAX_ERROR + 1,
        USAGE = MIN_ERROR,
        UNHANDLED_EXCEPTION,
        MAX_ERROR = UNHANDLED_EXCEPTION
    };

    static const char* error_strings[] = {
        "usage error",
        "an exception was thown and not handled within the control loop "
    };

    char* Program;

    void
    usage( )
    {
        std::cerr << "Usage: " << Program
                  << " [--force] [--relax] [--data-valid] [--verbose] "
                     "[--use-mmap] [--bs=<size>] [--no-metadata-check] "
                     "frame_file [ frame_file ... ]"
                  << std::endl
                  << std::endl
                  << "\t--force - Continue processing after an error has been "
                     "encountered"
                  << std::endl
                  << "\t--relax - Use a relaxed interpretation of the frame "
                     "specification"
                  << std::endl
                  << "\t--data-valid - Check the dataValid bit in FrAdcData "
                     "structures for non-zero values"
                  << std::endl
                  << "\t--verbose - Display file name and exit status of each "
                     "file processed"
                  << std::endl
                  << "\t--checksum-frames - Run checksums on individusl frames"
                  << std::endl
                  << "\t--use-mmap - Use memory mapped io" << std::endl
                  << "\t--bs - number of 1k blocks to use for io" << std::endl
                  << "\t--no-metadata-check - disable checking of metadata"
                  << std::endl
                  << std::endl;
        for ( unsigned int e = FrameCPP::Verify::NO_ERROR;
              e <= FrameCPP::Verify::MAX_ERROR;
              ++e )
        {
            std::cerr << "\t" << e << " - "
                      << FrameCPP::Verify::StrError(
                             (FrameCPP::Verify::error_type)e )
                      << std::endl;
        }
        for ( unsigned int e = MIN_ERROR; e <= MAX_ERROR; ++e )
        {
            std::cerr << "\t" << e << " - " << std::flush
                      << error_strings[ e - MIN_ERROR ] << std::endl;
        }
    }
} // namespace

int
main( int ArgC, char** ArgV ) try
{
    Program = ArgV[ 0 ];

    char**           argv( &ArgV[ 1 ] );
    FrameCPP::Verify verifier;
    bool             force( false );
    bool             verbose( false );
    INT_4U           exit_status = FrameCPP::Verify::NO_ERROR;

    //---------------------------------------------------------------------
    // Disable memory mapped I/O so failed reads can return without
    //   causing a signal.
    //---------------------------------------------------------------------
    verifier.UseMemoryMappedIO( false );
    //---------------------------------------------------------------------
    // Parse out the command line options
    //---------------------------------------------------------------------
    while ( *argv && ( **argv == '-' ) )
    {
        if ( strcmp( *argv, "--relax" ) == 0 )
        {
            verifier.Strict( false );
        }
        else if ( strcmp( *argv, "--relax-eof-checksum" ) == 0 )
        {
            verifier.MustHaveEOFChecksum( false );
        }
        else if ( strcmp( *argv, "--verbose" ) == 0 )
        {
            verbose = true;
        }
        else if ( strcmp( *argv, "--force" ) == 0 )
        {
            force = true;
        }
        else if ( strcmp( *argv, "--data-valid" ) == 0 )
        {
            verifier.CheckDataValid( true );
        }
        else if ( strcmp( *argv, "--checksum-frames" ) == 0 )
        {
            verifier.CheckFrameChecksum( true );
        }
        else if ( strcmp( *argv, "--use-mmap" ) == 0 )
        {
            verifier.UseMemoryMappedIO( true );
        }
        else if ( strncmp( *argv, "--bs=", 5 ) == 0 )
        {
            verifier.BufferSize( atol( &( ( *argv )[ 5 ] ) ) * 1024 );
        }
        else if ( strcmp( *argv, "--no-metadata-check" ) == 0 )
        {
            verifier.ValidateMetadata( false );
        }
        else
        {
            usage( );
            exit( USAGE );
        }
        ++argv;
    }
    if ( *argv == (char*)NULL )
    {
        usage( );
        exit( USAGE );
    }

    while ( *argv != (char*)NULL )
    {
        if ( verbose )
        {
            std::cout << *argv << std::flush;
        }
        INT_4U new_exit_status = verifier( *argv );
        if ( verbose )
        {
            std::string errorinfo( verifier.ErrorInfo( ) );
            std::cout << " " << new_exit_status;
            if ( errorinfo.length( ) > 0 )
            {
                std::cout << std::endl << errorinfo;
            }
            std::cout << std::endl << std::flush;
        }
        //------------------------------------------------------------------
        // Check to see if processing should continue
        //------------------------------------------------------------------
        if ( ( force == false ) &&
             ( new_exit_status != FrameCPP::Verify::NO_ERROR ) )
        {
            //----------------------------------------------------------------
            // No, so just exit with the exit status
            //----------------------------------------------------------------
            exit( new_exit_status );
        }
        if ( exit_status < new_exit_status )
        {
            exit_status = new_exit_status;
        }
        ++argv;
    }
    exit( exit_status );
}
catch ( std::exception& e )
{
    std::cerr << std::endl
              << "ABORT: Caught exception: " << e.what( ) << std::endl;
    exit( UNHANDLED_EXCEPTION );
}
catch ( ... )
{
    std::cerr << std::endl << "ABORT: Caught unknown exception: " << std::endl;
    exit( UNHANDLED_EXCEPTION );
}
