# Copyright 1999-2016. Parallels IP Holdings GmbH. All Rights Reserved.
package ContentTransport::Rsync;

use strict;
use bigint;

use Logging;
use Storage::Storage;
use ContentTransport::ContentTransport;

use vars qw|@ISA|;

@ISA = qw|ContentTransport::ContentTransport|;

sub new {
  my $self = {};
  bless( $self, shift );
  $self->_init(@_);
  return $self;
}

sub _init{
  my( $self, $options, $storagepolicy ) = @_;
  $self->SUPER::_init( $options );
  $self->{storage} = $storagepolicy;
}

sub getContentTransportDescription {
  my $self = shift;
  my $descriptionNode = XmlNode->new( 'rsync' );
  $descriptionNode->setAttribute( 'host', $self->{options}->{'host'} );
  $descriptionNode->setAttribute( 'port', $self->{options}->{'port'} ) if exists ( $self->{options}->{'port'} );
  $descriptionNode->setAttribute( 'login', $self->{options}->{'login'} );
  $descriptionNode->setAttribute( 'password', $self->{options}->{'passwd'} );
  return $descriptionNode;
}

sub addContent {
  my $self = shift;
  my $cid_type = shift;
  my $proposedId = shift;
  my %options = @_;

  return if $self->_skipContent(%options);

  return unless (-d $options{'directory'});

  if ( $options{'checkEmptyDir'} ) {
    return unless $self->{storage}->checkDirForArchive($options{'directory'}, [], $options{'include_hidden_files'});
  }

  return $self->_makeCidRsyncNode( $cid_type, $options{'directory'},
                                              $options{'include'},
                                              $options{'no_recursion'} );
}

sub _makeCidRsyncNode{
  my ($self, $cid_type, $directory, $include, $no_recursion) = @_;
  # '$include' could contain filename inside '$directory'.

  my $cid = XmlNode->new( 'cid-rsync' );
  $cid->setAttribute( 'type', $cid_type );

  my $path = $directory;
  if ( defined $include ) {
    my @includes = @{$include};
    my $subpath = $includes[0];
    if ($subpath ne '.') {
      $path .= '/' if $path and substr( $path, -1, 1 ) ne '/';
      $path .= $subpath;
    }
  }
  my $cmd = "du -sb";
  if ( defined $no_recursion ) {
    $cmd .= " -S";
  }
  $cmd .= " $path";
  my $sizes = `$cmd`;

  my $unpacksize = 0;
  for(split /[\r\n]+/,$sizes) {
    my ($number, $file) = split /\t/,$_,2;
    $unpacksize += $number;
  }

  if ( -d $path and substr( $path, -1, 1 ) ne '/') {
    $path .= '/';
  }

  $cid->setAttribute( 'unpacksize', $unpacksize );
  $cid->setAttribute( 'path', $path );
  return $cid;
}


1;