package Distribution::TransportAgent::SFTP;

use strict;

use base 'Distribution::TransportAgent';

use Common::Assert;
use Data::Dumper;
use Proc::Background;

use constant TUNNELIER => 'D:/Tunnelier/sftpc';

sub _init {
    my $self = shift;

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

    assert( $self->{_host}, "Hostname required for SFTP" );
    assert( $self->{_user} && ( $self->{_passwd} || $self->{_authfile} ), "User credentials required for SFTP" );

    return $self;
}

sub _transfer {
    my $self   = shift;
    my $source = shift;
    my $dest   = shift;
    my $result;

    my $transferedBytes = 0;
    my $complete        = 0;

    my $sftp_cmd = $self->_putCmd( $source, $dest );

    Common::Log::Debug("CMD: $sftp_cmd");

    my $process = Proc::Background->new( { die_upon_destroy => 1 }, $sftp_cmd );
    $result = $process->wait();

    Common::Log::Print("RESULT: $result: $!");

    $complete = defined($result) && $result == 0 ? 1 : 0;

    # TODO implement some progress monitoring
    return ( $complete, 0 );
}

sub _get {
    my $self   = shift;
    my $source = shift;
    my $dest   = shift;
    my $result;

    my $transferedBytes = 0;
    my $complete        = 0;

    my $sftp_cmd = $self->_getCmd( $source, $dest );
    Common::Log::Print("CMD: $sftp_cmd");

    $result = system($sftp_cmd );

    #$result = 0;
    Common::Log::Print("RESULT: $result");

    $complete = $result ? 0 : 1;

    # TODO implement some progress monitoring
    return ( $complete, 0 );
}

sub _putCmd {
    my $self   = shift;
    my $source = shift;
    my $dest   = shift;
    my $port   = $self->{_port} ? " -port=$self->{_port} " : "";

    my $auth =
      $self->{_passwd}
      ? " -pw=$self->{_passwd} "
      : " -keypairFile=$self->{_authfile} ";
    my $resume = $self->{_noResume} ? '' : '-r';

    my $cmd =
        TUNNELIER
      . ' -hostKeyFile=C:/host.keys '
      . " $port "
      . " -user=$self->{_user} "
      . " $auth "
      . ' -cmd="put '
      . $source . ' '
      . $dest
      . ' -fg -b -s -o '
      . $resume . ' " '
      . $self->{_host};

    Common::Log::Debug("  - SFTP Command: $cmd");

    return $cmd;
}

sub _getCmd {
    my $self   = shift;
    my $source = shift;
    my $dest   = shift;
    my $port   = $self->{_port} ? " -port=$self->{_port} " : "";

    my $auth =
      $self->{_passwd}
      ? " -pw=$self->{_passwd} "
      : " -keypairFile=$self->{_authfile} ";

    my $resume = $self->{_noResume} ? '' : '-r';

    my $cmd =
        TUNNELIER
      . ' -hostKeyFile=C:\host.keys '
      . " $port "
      . "-user=$self->{_user} "
      . $auth
      . ' -cmd="get \"'
      . $source . '\" \"'
      . $dest
      . '\" -fg '
      . $resume
      . ' -o " '
      . $self->{_host};

    Common::Log::Debug("  - SFTP Command: $cmd");

    return $cmd;
}

1;
