#!/usr/bin/perl

use strict;
use warnings;
use open ':std', ':encoding(UTF-8)';

use Net::FTP;
use YAML::Syck;
use POSIX (qw/strftime/);

use lib '/app/tools/common/lib';
use Common::Session;

my ( $opt, $usage ) = clopt(
    [ 'host|h=s'    => 'FTP host to connect', { 'default' => 'upload' } ],
    [ 'user|u=s'    => 'FTP user to test' ],
    [ 'timeout|t=i' => 'FTP timeout',         { 'default' => 5 } ],
    [ 'file|f=s'    => 'Path to file to test put' ],
    [ 'nols|n'      => 'Dont do a file list on the ftp' ],
    [ 'help|?'      => "print usage message and exit" ]
);

if ( $opt->help ) {
    logMessage( 'info', $usage->text, 'options' );
    exit 1;
}

my $conf = YAML::Syck::LoadFile('/app/tools/bookpub/conf/logins.yml');

print "-" x 80 . "\n";
print "Connecting to " . $opt->host . "\n";
print "-" x 80 . "\n";

foreach my $user ( @{ $conf->{'ftpusers'} } ) {
    my $ftp = Net::FTP->new( $opt->host . '.royaltyshare.com', 'Debug' => 1, 'Passive' => 1, 'Timeout' => $opt->timeout );
    die "Could not connect to " . $opt->host if not defined $ftp;
    next if defined $opt->user and $user->{'username'} ne $opt->user;

    my $start_t = time;

    print "-" x 80 . "\n";
    print "Testing $user->{'username'} connection\n";
    print "-" x 80 . "\n";

    $ftp->login( $user->{'username'}, $user->{'password'} );
    if ( $ftp->code >= 300 ) {
        print "ERROR - unable to connect to ftp site transfer.royaltyshare.com: " . $ftp->code . " " . $ftp->message . "\n";
    } else {
        $ftp->cwd;
        if ( $opt->file ) {
            my $file = $opt->file;
            $ftp->put($file);
            $ftp->delete($file);
        } elsif ( not $opt->nols ) {
            map { print "$_\n" } $ftp->ls;
        }
    }
    $ftp->close;

    my $ttc = time - $start_t;
    my $hhmmss = strftime( "\%H:\%M:\%S", gmtime($ttc) );
    print "$user->{'username'} connection $ttc seconds [ $hhmmss ]\n";

}

