#!/usr/bin/perl
# Data import wrapper script.
# Usage:
#   ./run_import.pl -f filename -i importID --exceptions exceptionsFilename
#
# This script is designed as a generic replacement for the various
# import_* scripts that have historically been used with the import-
# specific makefiles.  When you run 'make import' (or make test), this
# script will typically be called as follows:
#
#   test:
#         run_import.pl -c clientID -f template -i importID
#
#   import:
#         run_import.pl -c clientID -f template -i importID -e
#
# The '-i' parameter is used to define the import identifier, which is then
# used to lookup the import type (serviceID) associated with the import.
# Note that imports initiated from the command line won't have an importID,
# so in those cases use the '-s serviceID' (where serviceID is one of the
# service identifiers defined in Support::DataImport::RPSDataImport) to
# indicate which import module to use to handle the template.
#
# If you're manually running this script from the command line...
#  - You generally want to always have a clientID, a template name, and
#    an importID or serviceID.
#  - If you omit the clientID, then we'll try to locate the import based
#    on the current directory.
#  - For a UI-based import (e.g., has an importID), you can override the
#    serviceID associated with the importID by using the '-s' option.
#    This can be useful if for some reason the template was mis-identified.
#
# Once this script functioning properly, all we need to do is simply
# replace the various 'import_' references in the template makefiles
# with this single script.  Also, rps_dataimport.pl will need to be
# updated to add-in the importID where possible.
#
# templates/{importType}/makefile.in -- replace import_ references
#   with run_import.pl
#
use warnings;
use strict;
use Getopt::Long;
use Data::Dumper;
use Cwd;

use lib '/app/tools/support/lib';
use Support::DataImport::RPSDataImport;
use Support::DB::Item::DataImport;
use Support::DB::Item::DataImportFile;

use lib '/app/tools/common/lib';
use Common::RSApp;

my %args = ();
parseCommandLine(\%args);

print "D:run_import.pl: args = ". Dumper(\%args) . "\n";

my $inputFile = $args{file_name};
my $clientID  = $args{client_id};
my $importID  = $args{import_id};
my $serviceID = $args{service_id};
my $execMode  = $args{exec_mode};
my $licenseFile = $args{license_file};

my $import; # DataImport object


# The clientID really should be required ...
#
if ( !$clientID ) {

    my $appSingleton = Common::RSApp->new(clientID => 202);
    my $cdbo         = Common::RSApp::GetCommonDB();
    my $dbo          = Common::RSApp::GetClientDB();

    if ( !$importID ) {
        # Is there an import associated with the current directory?
        #
        my $cwd = `pwd`;
        my $sql = "SELECT import_id FROM data_import WHERE path=".$cdbo->DBQuote($cwd);
        my $sth = $cdbo->DoCmd($sql);
        my($_importID) = $sth->fetchrow_array();
        print "D: This directory is associated with import $_importID\n";
        $importID = $_importID;
    }

    $import   = Support::DB::Item::DataImport->Lookup( import_id => $importID );
    $clientID = $import->client_id;
    die("Invalid importID $importID") if ( !$import );
}

if ( $importID && !$import ) {
    my $appSingleton = Common::RSApp->new(clientID => $clientID);
    my $cdbo         = Common::RSApp::GetCommonDB();
    my $dbo          = Common::RSApp::GetClientDB();

    $import = Support::DB::Item::DataImport->Lookup( import_id => $importID );
    #die("Invalid importID $importID") if ( !$import );
    print "ERROR: Invalid importID $importID !!!\n" if ( !$import ); # XXX
    $serviceID = $import->service_id if ( !$serviceID );
}
else {
    print "ERROR: No importID or importID $importID is invalid !!!\n";
}

my $codeName = Support::DataImport::RPSDataImport->CodeName($serviceID);

die("run_import.pl: No importer module found for import type $serviceID !!!") if ( !$codeName );

my %importArgs = (
    name => $inputFile,
    client_id => $clientID,
    exec_mode => $execMode,
);
$importArgs{license_file} = $licenseFile if ( $licenseFile );


my $class;
my $pkg = $codeName;
eval "require $pkg";
if ( !$@ ) {
    $class = $pkg;
    print "D: package $pkg exists !!!\n";

    my $template = $class->new( %importArgs );

    my $st = $template->loadMemory()

}
else {
    print "ERROR: package $pkg not found !!!\n";
}


#====================
# --- Subroutines ---
#====================
sub parseCommandLine {
    my( $a ) = @_;
    my $clientID;
    my $filename;
    my $importID;
    my $execMode;
    my $serviceID;
    my $licenseFile; # licensing income only

    if ( ! GetOptions(
        'c=i'    => \$clientID,
        'f=s'    => \$filename,
        'e|exec' => \$execMode,
        'i|import_id=i'  => \$importID,
        's|service_id=i' => \$serviceID,
        'l=s'    => \$licenseFile,
    )) {
        die("An error has occurred while parsing arguments, aborting\n");
    }

    $a->{client_id}   = $clientID;
    $a->{file_name}   = $filename;
    $a->{import_id}   = $importID;
    $a->{service_id}  = $serviceID;
    $a->{exec_mode}   = $execMode;
    $a->{license_file} = $licenseFile;
}

sub usage {
   my $errstr = shift;
   my $text = ($errstr) ? "ERROR: $errstr\n" : '';
   $text .= "Usage $0 [-c <clientID> -f <inputFile>] [-i <importID>] [-e]\n";
   return $text;
}
