#!/usr/bin/perl

use strict;

use lib '/app/tools/common/lib';
use Common::Util;
use Common::RSApp;

use lib '/app/tools/bookpub/lib';
use BookPub::Sale::File;

my $client_id = $ARGV[0] || usage('missing client_id');
my $filePath  = $ARGV[1] || usage('missing file path');
$filePath .= '/' unless ( $filePath =~ /\.\w+$/ );

my $appSingleton = Common::RSApp->new( clientID => $client_id );

if ( -d $filePath ) {
    my $count = 0;
    opendir( D, $filePath ) or die "can't open dir: $!\n";
    foreach ( grep !/^\./, readdir(D) ) {
        print upload( $filePath . $_ ) ? 'ok' : 'error';
        print "\n";
        $count++;
        sleep(2);
    }
    print "$count files uploaded\n";
} else {
    print upload($filePath) ? 'ok' : 'error';
    print "\n";
}

sub upload {
    my $file = shift;
    my $fh;
    open( $fh, $file ) or die "can't open file: $!\n";
    my $md5sum = Common::Util::md5sum($fh);
    close($fh);

    return BookPub::Sale::File::SimpleUploadFromShell(
        client_id => $client_id,
        filepath  => $file,
        md5_sum   => $md5sum,
    );
}

sub usage {
    my $msg = shift;
    print "error: $msg\n" if $msg;
    print "usage: $0 CLIENT_ID PATH_TO_FILE_OR_DIR\n";
    exit();
}
