/*  Ztest - verify integrity of compressed files
    Copyright (C) 2010, 2011, 2012, 2013, 2014 Antonio Diaz Diaz.

    This program is free software: you can 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 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#define _FILE_OFFSET_BITS 64

#include <cerrno>
#include <climits>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <list>
#include <string>
#include <vector>
#include <dirent.h>
#include <fcntl.h>
#include <stdint.h>
#include <unistd.h>
#include <sys/stat.h>
#if defined(__MSVCRT__) || defined(__OS2__)
#include <io.h>
#endif

#include "arg_parser.h"
#include "rc.h"
#include "zutils.h"

#ifndef O_BINARY
#define O_BINARY 0
#endif


namespace {

#include "recursive.cc"

void show_help()
  {
  std::printf( "Ztest verifies the integrity of the specified compressed files.\n"
               "Uncompressed files are ignored. If no files are specified, the integrity\n"
               "of compressed data read from standard input is verified. Data read from\n"
               "standard input must be all in the same compression format.\n"
               "\nThe supported formats are bzip2, gzip, lzip and xz.\n"
               "\nNote that some xz files lack integrity information, and therefore can't\n"
               "be verified as reliably as the other formats can.\n"
               "\nUsage: ztest [options] [files]\n"
               "\nExit status is 0 if all compressed files verify OK, 1 if environmental\n"
               "problems (file not found, invalid flags, I/O errors, etc), 2 if any\n"
               "compressed file is corrupt or invalid.\n"
               "\nOptions:\n"
               "  -h, --help                 display this help and exit\n"
               "  -V, --version              output version information and exit\n"
               "      --format=<fmt>         force given format (bz2, gz, lz, xz)\n"
               "  -N, --no-rcfile            don't read runtime configuration file\n"
               "  -q, --quiet                suppress all messages\n"
               "  -r, --recursive            operate recursively on directories\n"
               "  -v, --verbose              be verbose (a 2nd -v gives more)\n"
               "      --bz2=<command>        set compressor and options for bzip2 format\n"
               "      --gz=<command>         set compressor and options for gzip format\n"
               "      --lz=<command>         set compressor and options for lzip format\n"
               "      --xz=<command>         set compressor and options for xz format\n" );
  show_help_addr();
  }


int open_instream( std::string & input_filename )
  {
  const int infd = open( input_filename.c_str(), O_RDONLY | O_BINARY );
  if( infd < 0 )
    show_error2( "Can't open input file", input_filename.c_str() );
  return infd;
  }


int ztest_stdin( const int infd, int format_index,
                 const std::vector< const char * > & ztest_args )
  {
  const uint8_t * magic_data = 0;
  int magic_size = 0;
  if( format_index < 0 )
    format_index = test_format( infd, &magic_data, &magic_size );
  const char * const compressor_name = get_compressor_name( format_index );
  if( !compressor_name )
    { show_error( "Unknown data format read from stdin." ); return 2; }
  int fda[2];				// pipe from feeder
  if( pipe( fda ) < 0 )
    { show_error( "Can't create pipe", errno ); return 1; }

  const pid_t pid = fork();
  if( pid == 0 )			// child1 (compressor feeder)
    {
    if( close( fda[0] ) != 0 ||
        !feed_data( infd, fda[1], magic_data, magic_size ) )
      _exit( 1 );
    if( close( fda[1] ) != 0 )
      { show_close_error(); _exit( 1 ); }
    _exit( 0 );
    }
  if( pid < 0 )				// parent
    { show_fork_error( "data feeder" ); return 1; }

  const pid_t pid2 = fork();
  if( pid2 == 0 )			// child2 (compressor)
    {
    if( dup2( fda[0], STDIN_FILENO ) >= 0 &&
        close( fda[0] ) == 0 && close( fda[1] ) == 0 )
      {
      const std::vector< std::string > & compressor_args =
        get_compressor_args( format_index );
      const int size = compressor_args.size();
      const int size2 = ztest_args.size();
      const char ** const argv = new const char *[size+size2+3];
      argv[0] = compressor_name;
      for( int i = 0; i < size; ++i )
        argv[i+1] = compressor_args[i].c_str();
      for( int i = 0; i < size2; ++i )
        argv[i+size+1] = ztest_args[i];
      argv[size+size2+1] = "-t";
      argv[size+size2+2] = 0;
      execvp( argv[0], (char **)argv );
      }
    show_exec_error( compressor_name );
    _exit( 1 );
    }
  if( pid2 < 0 )			// parent
    { show_fork_error( compressor_name ); return 1; }

  close( fda[0] ); close( fda[1] );
  const bool isgzxz = ( format_index == fmt_gz || format_index == fmt_xz );
  int retval = wait_for_child( pid2, compressor_name, 1, isgzxz );
  if( retval == 0 && wait_for_child( pid, "data feeder" ) != 0 )
    retval = 1;
  return retval;
  }


int ztest_file( const int infd, int format_index,
                const std::string & input_filename,
                const std::vector< const char * > & ztest_args )
  {
  const uint8_t * magic_data = 0;
  int magic_size = 0;
  if( format_index < 0 )
    format_index = test_format( infd, &magic_data, &magic_size );
  const char * const compressor_name = get_compressor_name( format_index );
  if( !compressor_name )
    return 0;				// skip this file
  const pid_t pid = fork();

  if( pid == 0 )			// child (compressor)
    {
    const std::vector< std::string > & compressor_args =
      get_compressor_args( format_index );
    const int size = compressor_args.size();
    const int size2 = ztest_args.size();
    const char ** const argv = new const char *[size+size2+5];
    argv[0] = compressor_name;
    for( int i = 0; i < size; ++i )
      argv[i+1] = compressor_args[i].c_str();
    for( int i = 0; i < size2; ++i )
      argv[i+size+1] = ztest_args[i];
    argv[size+size2+1] = "-t";
    argv[size+size2+2] = "--";
    argv[size+size2+3] = input_filename.c_str();
    argv[size+size2+4] = 0;
    execvp( argv[0], (char **)argv );
    show_exec_error( compressor_name );
    _exit( 1 );
    }
  if( pid < 0 )				// parent
    { show_fork_error( compressor_name ); return 1; }

  const bool isgzxz = ( format_index == fmt_gz || format_index == fmt_xz );
  return wait_for_child( pid, compressor_name, 1, isgzxz );
  }

} // end namespace


int main( const int argc, const char * const argv[] )
  {
  enum { format_opt = 256, bz2_opt, gz_opt, lz_opt, xz_opt };
  int infd = -1;
  int format_index = -1;
  bool recursive = false;
  std::string input_filename;
  std::list< std::string > filenames;
  std::vector< const char * > ztest_args;	// args to ztest, maybe empty
  invocation_name = argv[0];
  program_name = "ztest";

  const Arg_parser::Option options[] =
    {
    { 'h', "help",          Arg_parser::no  },
    { 'N', "no-rcfile",     Arg_parser::no  },
    { 'q', "quiet",         Arg_parser::no  },
    { 'r', "recursive",     Arg_parser::no  },
    { 'v', "verbose",       Arg_parser::no  },
    { 'V', "version",       Arg_parser::no  },
    { format_opt, "format", Arg_parser::yes },
    { bz2_opt,    "bz2",    Arg_parser::yes },
    { gz_opt,     "gz",     Arg_parser::yes },
    { lz_opt,     "lz",     Arg_parser::yes },
    { xz_opt,     "xz",     Arg_parser::yes },
    {  0 ,  0,              Arg_parser::no  } };

  const Arg_parser parser( argc, argv, options );
  if( parser.error().size() )				// bad option
    { show_error( parser.error().c_str(), 0, true ); return 1; }

  maybe_process_config_file( parser );

  int argind = 0;
  for( ; argind < parser.arguments(); ++argind )
    {
    const int code = parser.code( argind );
    if( !code ) break;					// no more options
    const char * const arg = parser.argument( argind ).c_str();
    switch( code )
      {
      case 'h': show_help(); return 0;
      case 'N': break;
      case 'q': verbosity = -1; ztest_args.push_back( "-q" ); break;
      case 'r': recursive = true; break;
      case 'v': if( verbosity < 4 ) ++verbosity;
                ztest_args.push_back( "-v" ); break;
      case 'V': show_version(); return 0;
      case format_opt: format_index = parse_format_type( arg ); break;
      case bz2_opt: parse_compressor( arg, fmt_bz2, 1 ); break;
      case gz_opt: parse_compressor( arg, fmt_gz, 1 ); break;
      case lz_opt: parse_compressor( arg, fmt_lz, 1 ); break;
      case xz_opt: parse_compressor( arg, fmt_xz, 1 ); break;
      default : internal_error( "uncaught option." );
      }
    } // end process options

#if defined(__MSVCRT__) || defined(__OS2__)
  setmode( STDIN_FILENO, O_BINARY );
  setmode( STDOUT_FILENO, O_BINARY );
#endif

  for( ; argind < parser.arguments(); ++argind )
    filenames.push_back( parser.argument( argind ) );

  if( filenames.empty() ) filenames.push_back("-");

  int retval = 0;
  bool error = false;
  while( next_filename( filenames, input_filename, error, recursive ) )
    {
    if( input_filename.empty() ) infd = STDIN_FILENO;
    else
      {
      infd = open_instream( input_filename );
      if( infd < 0 ) { error = true; continue; }
      }

    int tmp;
    if( infd == STDIN_FILENO )
      tmp = ztest_stdin( infd, format_index, ztest_args );
    else tmp = ztest_file( infd, format_index, input_filename, ztest_args );
    if( tmp > retval ) retval = tmp;

    if( input_filename.size() ) { close( infd ); infd = -1; }
    }

  if( std::fclose( stdout ) != 0 )
    {
    show_error( "Can't close stdout", errno );
    error = true;
    }
  if( error && retval == 0 ) retval = 1;
  return retval;
  }