#!/usr/bin/perl -w

use strict;
use Getopt::Std;
use File::Basename;

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

use lib '/app/tools/metadata/lib';
use Metadata::Importer;

MAIN: {
    my %opts = parseCommandLine();

    Common::Log::Debug("Starting Metadata Import");
    Common::Log::Debug("  ++ Dry run only, not storing result ++")
      unless ( $opts{execute} );

    open( INFILE, $opts{infile} );
    my $fh           = \*INFILE;
    my $appSingleton = new Common::RSApp( clientID => $opts{clientID} );
    my $importer     = new Metadata::Importer(
        clientID => $opts{clientID},
        execute  => $opts{execute},
        fh       => $fh,
        infile   => $opts{infile}
    ) || die("Failed to create Metadata Controller");

    if ( $opts{stage} ) {
        $importer->import_file();
    } elsif ( $opts{validate} ) {
        $importer->validate();
    } elsif ( $opts{store} ) {
        $importer->store();
    } else {
        usage("-s, -v, or -x required");
    }

}

sub parseCommandLine {
    my %opt;
    my %config;
    my $infile;

    getopts( 'c:ds:vx', \%opt ) || usage();

    #
    # Check for options and validate them
    #

    # Client ID
    usage("ClientID Required") unless ( $opt{c} );
    usage("ClientID must be numeric") unless ( $opt{c} =~ /^\d+$/ );

    $config{clientID} = $opt{c};
    $config{infile}   = $opt{s};
    $config{stage}    = $opt{s} ? 1 : undef;
    $config{validate} = $opt{v};
    $config{store}    = $opt{x};
    $ENV{CLIENT_ID}   = $ENV{DEBUG} = $config{clientID};
    $ENV{DEBUG}       = 0 unless ( $opt{d} );

    # Input file
    usage("Unable to read input file") unless ( !$config{stage} || -r $config{infile} );

    return %config;
}

sub usage {
    my $errstr = shift;
    printf STDERR "%s%s",
      $errstr ? "ERROR: $errstr\n" : "",
      "USAGE: "
      . basename($0)
      . " -c <clientID> [-d] [-s inputfile] [-v] [-x]\n"
      . "   -c - Client ID (required)\n"
      . "   -d - enable debugging\n"
      . "   -s - Import to staging tables (step 1)\n"
      . "   -v - Validate the staged data (step 2)\n"
      . "   -x - Integrate the staging into database (step 3)\n";

    exit 1;
}
