use lib (
    '/home/raj/perl5/lib/perl5',
    '/home/raj/apps/HILIS4/lib',
);
use LIMS::Local::Utils;
use Data::Printer alias => ddp;
use Modern::Perl;
use Net::FTP;
use IO::All;

use constant LOGFILE => '/home/raj/crons/genomics_transfer.log';

my $timestamp = LIMS::Local::Utils::time_now();

my $local_filename = '219_2016_0810_150003.xml';

{
    my %params = (
        local_filename  => '/tmp/' . $local_filename,
        remote_filename => $local_filename,
        server_addr     => '163.160.107.109',
        username        => 'HMDS',
        password        => 'dmw@kY4jzu$Hx5p',
        cwd             => 'HILIS_GEL', # destination_dir for genomics data
        passive_mode    => 1,
        ascii_mode      => 1,

   ); # ddp \%params;

    # ftp file (returns str on failure, undef on success):
    my $rtn = ftp_file(\%params); # ddp $rtn;
    if ($rtn) { # ddp $rtn;
        say $rtn;
    }
    else {
        my $msg = $timestamp->strftime('%Y-%m-%d %T') . ': '
			. $local_filename . "\n"; say $msg;
        io(LOGFILE)->append($msg);
	}
}

sub ftp_file {
    my $args = shift; # ddp $args; return;
    # can pass timeout as arg, default is 60 seconds if no value specified;
    # Timeout => $args->{timeout}
	my $ftp = Net::FTP->new( $args->{server_addr}, Debug => 1 )
    || return "Cannot connect to $args->{server_addr}: $@";

    if ($args->{username} && $args->{password}) {
        $ftp->login(@{$args}{qw/username password/})
        || return 'Cannot login - ' . $ftp->message;
    }
	$ftp->binary() unless $args->{ascii_mode};
    $ftp->passive(1) if $args->{passive_mode};
    $ftp->cwd($args->{cwd}) if $args->{cwd};

	$ftp->put($args->{local_filename}, $args->{remote_filename})
    # need to return NOW, or err message() will be replaced by outcome of quit():
    || return 'FTP error - ' . $ftp->message;

    $ftp->quit;

    return 0; # don't return message() here - will be result of quit() eg 'goodbye'
}
