package Distribution::Delivery::Fuga;

use strict;

use lib '/app/tools/distribution/lib';
use base 'Distribution::Delivery';

use File::Basename;

sub _semaphore {
    my $self = shift;

    Common::Log::Print("**** Semaphore ****");

    return 1 if ( $self->transferFailed() );

    my $packagePath = $self->_getLocalPackagePath();
    my $remotePath  = $self->_getRemoteSemaphorePath();

    my @albums = $self->_getDeliveredAlbums($packagePath);

    foreach my $album (@albums) {
        my $destinationPath = "$remotePath/$album";
        my $sourcePath      = "$packagePath/$album";

        Common::Log::Debug(" - Source: $sourcePath, Dest: $destinationPath");

        unless ( $self->_putSemaphore( $sourcePath, $destinationPath ) ) {
            Common::Log::Print("Delivery Failed!");
            $self->{_transferFailed} = 1;
            return unless $self->_retryDelivery();
        }
    }

    return 1;
}

sub _putSemaphore {
    my $self        = shift;
    my $source      = shift;
    my $destination = shift;

    my $upc = basename($source);
    $source = "$source/$upc.complete";

    my $transportAgent = $self->_getTransportAgent();

    # Create the semaphore file if it doesn't exist already
    unless ( -f $source ) {
        open( FILE, ">$source" );
        close(FILE);
    }

    if ( !-f $source ) {
        print STDERR "Could not create semaphore file: $source\n";
        return 0;
    }

    return $transportAgent->deliver( $source, $destination );
}

sub _getDeliveredAlbums {
    my $self = shift;
    my $dir  = shift;

    opendir( DIR, $dir ) || die "can't opendir $dir: $!";
    my @albums = grep { /^\d+$/ && -d "$dir/$_" } readdir(DIR);
    closedir DIR;

    return @albums;
}

1;
