#!/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 Getopt::Long;

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

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

# Get the options
my $HELP;
if (!GetOptions('h|?|help'  => \$HELP)) { usage(1); }
my $arg=shift(@ARGV);
while ($arg =~ /^-/) {
  push (@{$cmdref->{arg}}, $arg);
  $arg=shift(@ARGV);
}
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}},$_;
}

push (@{$cmdref->{arg}}, @ARGV);     # get the rest of the arguments

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