#!/usr/bin/perl

use strict;
use Getopt::Std;

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

$| = 1;

# Parse the command-line.
#
my ( $clientID, $inputFile, $module ) = parseCommandLine();

eval "require $module";
die "can't include $module - $@\n" if $@;

# Instantiate the application singleton object.
#
my $appSingleton = Common::RSApp->new( clientID => $clientID );

# Scan the input file, and build the data structure of updates.
#
my $importer = $module->new();
$importer->importFile($inputFile);

# -------------------------------------------------------------
# Subroutines
# -------------------------------------------------------------

sub parseCommandLine {
    my %opt;
    getopts( 'c:f:M:', \%opt );

    my $inputFile = $opt{f};
    my $clientID  = $opt{c};
    my $module    = $opt{M};
    $module =~ s/\.pm$//;

    unless ( $clientID =~ /^\d+$/ && $clientID > 0 ) {
        die usage("You must specify a valid client ID");
    }

    unless ($inputFile) {
        die usage("You must specify a catalog file to import");
    }

    unless ( -e $inputFile ) {
        die usage("The specified catalog file does not exist");
    }

    unless ( -e "$module.pm" ) {
        die usage("Can't find $module.pm");
    }

    return ( $clientID, $inputFile, $module );
}

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