package LFTP;

use strict;
use warnings;
use parent 'Expect';

BEGIN {
  $LFTP::VERSION = '0.2';
  $LFTP::timeout = undef();
}

=head1 NAME

LFTP - A Expect wrapper for lftp

=head1 SYNOPSIS

Start the lftp process
  $lftp = LFTP->new({'lftp_bin' => '/bin/lftp',
                     'timeout' => '2',
  });

To connect
  $lftp->command("open -u $user,$password -p $port $host");

Enter a dir
  $lftp->command("cd dir");

Do a ls
  my @list = $lftp->command("ls");

Do a ls with timeout
  my @list = $lftp->command("ls",5);

Set global timeout to 5 seconds
  $lftp->timeout(5);

Quit the lftp process
  $lftp->command("quit");

=head1 DESCRIPTION

This module is made to make it easier to use lftp with perl.

=over 4

=item lftp_bin

Path to your lftp binary file. Mandatory.

=item timeout

A timeout for how many seconds it should wait for new() to launch the lftp process. It will also change the global timeout for all the commands. If not spesified, the timeout will be 'indefinite'.

=back

=head1 METHODS

=over 4

=item new()

Spawns a new lftp process

=cut

sub new {
	my ($class,$args) = @_;
	$LFTP::timeout = $args->{'timeout'} || undef();
	my $bin = $args->{'lftp_bin'} || undef();

	my $exp = new Expect;
	$exp->raw_pty(0);
	$exp->log_stdout(0);
	$exp->spawn("$bin -e 'set prompt \"LFTP perl Module>\"'") or die "Cannot spawn: $!\n";
	$exp->expect($LFTP::timeout,"-re", "LFTP perl Module>");
	$exp->send("set interactive no\n");
	$exp->expect($LFTP::timeout,"-re", "LFTP perl Module>");
	return bless($exp);
}

=item command()

Send a command to the lftp process. It will return an array with the response. It's also possible to run single commands with temporary timeout (5 seconds) like this: command("ls",5);

=cut

sub command {
	my $exp = shift;
	my $command = shift;
	my $timeout = shift || $LFTP::timeout;
	$exp->send("$command\r");
	$exp->expect($timeout, "-re", "LFTP perl Module>");
	my $list = $exp->before();
	$list =~ s/\R/SPLITXXXXSPLIT/g;
	$list =~ s/^ //g;
	my @list2 = split (/SPLITXXXXSPLIT/,"$list");
	return @list2;
}

=tiem timeout()

With no argument it will return the current timeout. With argument it will change the global timeout.

=cut

sub timeout {
	my ($exp,$timeout) = @_;
	$LFTP::timeout = $timeout if $timeout;
	return $LFTP::timeout;
}

1;

__END__

=back

=head1 AUTHOR

Idar Lund <idar.lund@gmail.com>

=cut
