#!/usr/bin/perl 
#use Net::SFTP::Foreign;
use XML::Simple;
my $xml = new XML::Simple;
use Net::SFTP::Foreign;
use Net::SSH2;
use File::Basename;
my $Error = "";
my $return_code=0;
$config_file = $ARGV[0];
my $data = $xml->XMLin($config_file);
my $ssh2 = Net::SSH2->new();
$ssh2->connect($data->{host},$data->{port}) or $Error = "CRITICAL: SFTP test is failed. - ERROR: Cannot connect to SFTP.";
if ($Error ne "") { print $Error; exit 2; }
$ssh2->auth_password($data->{user}, $data->{password})or $Error = "CRITICAL: SFTP test is failed. - ERROR: Incorrect password.";
if ($Error ne "") { print $Error; exit 2; }
$sftp = Net::SFTP::Foreign->new(ssh2 => $ssh2,backend => 'Net_SSH2');
$sftp->error and $Error = "CRITICAL: SFTP test is failed. - ERROR: Cannot connect to SFTP: ". $sftp->error;
if ($Error ne "") { print $Error; exit 2; }
my $put_start_time=time;
$sftp->put($data->{filepath}, 'temp_file.tmp',copy_time => 0, copy_perm => 0) or $Error = "CRITICAL: SFTP test is failed. - ERROR: put command failed: " . $sftp->error;
my $put_end_time=time;
if ($Error ne "") { print $Error; exit 2; } 
my $total_put_time = $put_end_time - $put_start_time;
my $get_start_time=time;
$sftp->get('temp_file.tmp', dirname($data->{filepath})."\\temp_file.tmp") or $Error = "CRITICAL: SFTP test is failed. - ERROR: get command failed: " . $sftp->error;
my $get_end_time=time;
if ($Error ne "") { print $Error; exit 2; } 
my $total_get_time = $get_end_time - $get_start_time;
my $total_test_time = $total_put_time + $total_get_time;
$test_result = "File "  .basename( $data->{filepath}) ." of size ". $original_filesize ." is transfered in " . $total_put_time ." and received in " . $total_get_time . " Second/s";
my $original_filesize = -s $data->{filepath};
my $cloned_filesize = -s $data->{filepath}."\\temp_file.tmp";
#DELETE THE FILES
$sftp->remove('temp_file.tmp') or $Error = "ERROR: Remove remote temp file failed: " . $sftp->error;
my $filepath=dirname($data->{filepath})."\\temp_file.tmp";
unlink ($filepath) or $Error = "ERROR remove local temp file failed";
if ($Error ne "") { print $Error; exit 2; }
if ($original_filesize==$cloned_filesize)
{$test_result = "ERROR: There is an issue while uploading/downloading the file";
$return_code = 2;
}
else
{ if ($total_test_time<$data->{warning}) 
    { $return_code=0;} 
  elsif ($total_test_time>=$data->{critical}) 
    { $return_code=1; } 
  else
    { $return_code=2; }
}
print $test_result;
exit $return_code;