#!/usr/bin/env perl
# IBM(c) 2007 EPL license http://www.eclipse.org/legal/epl-v10.html

# Just like xcatclient, but needs to read a file in and pass it as $request->data

BEGIN { $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : -d '/opt/xcat' ? '/opt/xcat' : '/usr'; }
use lib "$::XCATROOT/lib/perl";
use File::Basename;
use xCAT::Client;
use xCAT::Utils;

use Getopt::Long;

sub usage {
    print "Usage: tabrestore <tablename>.csv\n";
    print "       tabrestore -a <tablename>.csv\n";
    print "       tabrestore [-?|-h|--help]\n";
    print "       tabrestore [-v|--version]\n";
    exit $_[0];
}

#my $bname = basename($0);
my $cmdref;
$cmdref->{command}->[0] = "tabrestore";

# Get the options
my $HELP;
if (
    !GetOptions(
        'h|?|help'  => \$HELP,
        'v|version' => \$VERSION,
        'a|addrows' => \$ADDROWS,
    )
  )
{ usage(1); }

my $arg = shift(@ARGV);
while ($arg =~ /^-/) {
    push(@{ $cmdref->{arg} }, $arg);
    $arg = shift(@ARGV);
}
if ($VERSION)
{
    my $version = xCAT::Utils->Version();
    print "$version\n";
    exit 0;
}
if ($HELP)
{
    usage;
}
if ($ADDROWS)
{
    $cmdref->{addrows}->[0] = "yes";
}

unless ($arg) { usage(2); }    # no filename specified

# Open the specified table file and put its contents in the data key
my $filename = $arg;
my $tabname  = basename($filename);
$tabname =~ s/\..*//;
$cmdref->{table}->[0] = $tabname;
my $fh;
unless (open($fh, $filename)) { print "Error: Unable to open $arg for reading.\n"; exit 3; }
while (<$fh>) {
    push @{ $cmdref->{data} }, $_;
}


xCAT::Client::submit_request($cmdref, \&xCAT::Client::handle_response);
exit $xCAT::Client::EXITCODE;

