#!/usr/bin/perl
#
# Pull assets from production and store them locally
#

use strict;

use Getopt::Std;
use File::Basename;

use lib '/app/tools/distribution/lib';

my %opt;
usage() unless getopts( 'c:r:x:qhldv', \%opt );

if ( $opt{l} ) {
    list_clients( $ARGV[0] );
}

if ( $opt{h} ) {
    usage();
}

my $matcher = new AssetSlurper(
    client_id    => $opt{c},
    report_email => $opt{r},
    error_email  => $opt{x},
    quiet        => $opt{q},
    verbose      => $opt{v},
    debug        => $opt{d},
    upcs         => \@ARGV
);

$matcher->run();

sub usage {
    my $prog = basename $0;

    print <<EofUSAGE;

usage: $prog [-c client_id] [-r report_email_address] [-x error_email_address] [-l client_name/pattern] [-h] [-d]
            -c - Client ID (if not specified then run for all clients)
            -r - Send summary report to this email instead of STDOUT
            -x - Send error report to this email instead of STDERR
            -l - List client ids (host pattern is optional)
            -d - display debug information to STDERR
            -v - display verbose debug information to STDERR
            -q - Do not output summary report
            -h - display this screen
EofUSAGE

    exit 1;
}

sub list_clients {
    my $host = shift;
    my $key;
    foreach $key ( sort { $a <=> $b } keys(%Common::RSDB::CLIENT_DB) ) {
        printf( "%-20s %-10s ID: %s\n", $Common::RSDB::CLIENT_DB{$key}->{db_name}, "($Common::RSDB::CLIENT_DB{$key}->{host_id})", $key )
          if ( !defined($host) || $Common::RSDB::CLIENT_DB{$key}->{db_name} =~ /$host/i );
    }
    exit 1;
}

package AssetSlurper;

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

use lib '/app/tools/common/lib';
use base 'Common::Script';

use lib '/app/tools/distribution/lib';
use Distribution::TransportAgent::SFTP;

use lib '/app/tools/mediaserve/lib';
use MediaServe::Server;
use MediaServe::DB::Item::AlbumFile;
use MediaServe::DB::Item::ProductTrackFile;

use Data::Dumper;
use File::Basename;

use constant HOST        => 'cm01';
use constant USER        => 'web';
use constant PASS        => 'getImages';
use constant MEDIA_DRIVE => 'F:';

sub is_already_running { }

sub _init {
    my $self = shift;
    my %args = @_;

    $self->SUPER::_init(@_);

    $self->{_upcs} = $args{upcs};

    die "Client ID required" unless ( $self->{_client_id} );

    die "No UPCs specified" unless ( $self->{_upcs} && ref( $self->{_upcs} ) && @{ $self->{_upcs} } );

    return $self;

}

sub _process {
    my $self = shift;

    $self->_getImageFiles();
    $self->_getAudioFiles();
}

sub _getImageFiles {
    my $self = shift;

    my $files;
    my $path;
    my $file;
    my $clientID = Common::RSApp::GetClientID();

    foreach my $upc ( @{ $self->{_upcs} } ) {
        $files = MediaServe::DB::Item::AlbumFile->LookupByUPC( upc => $upc );
        while ( $files->hasNext() ) {
            $file = $files->next();
            $path = MediaServe::Server::GetImagePath(
                mediaFileID => $file->media_file_id,
                clientID    => $clientID
            );

            $self->_fetchFile($path);
        }
    }

}

sub _getAudioFiles {
    my $self = shift;

    my $files;
    my $path;
    my $file;
    my $clientID = Common::RSApp::GetClientID();

    foreach my $upc ( @{ $self->{_upcs} } ) {
        $files = MediaServe::DB::Item::ProductTrackFile->LookupByUPC( upc => $upc );
        while ( $files->hasNext() ) {
            $file = $files->next();
            $path = MediaServe::Server::GetAudioPath(
                mediaFileID => $file->media_file_id,
                clientID    => $clientID
            );

            $self->_fetchFile($path);
        }
    }
}

sub _fetchFile {
    my $self = shift;
    my $path = shift;

    my $dir = dirname($path);

    system("mkdir -p $dir");

    my $agent = new Distribution::TransportAgent::SFTP(
        user   => USER,
        passwd => PASS,
        host   => HOST
    );

    die "Transfer failed" unless ( $agent->retrieve( "$path", MEDIA_DRIVE . "$path" ) );
}
