#!/usr/bin/perl
use warnings;
use strict;

=head1 NAME

Filesystem Gearman Worker

=cut


use Data::Dump qw(dump);

use lib '/srv/cloudstore/lib';
use CloudStore::API;
use WarnColor;

my $api = CloudStore::API->new('s1');

use Gearman::Worker;
my $worker = Gearman::Worker->new;
$worker->job_servers('127.0.0.1:4730');

=head2 send_file ~u2001/from.txt#~u2003/dir/new to.txt

=cut

$worker->register_function( send_file => sub {
	my ($job) = @_;

	my $work = $job->arg;
	chomp $work;
	warn "# send_file [$work]\n";

	my ( $from, $to ) = split(/#/,$work,2);
	
	my $f_uid = $1 if $from =~ s{~(\w+)/}{};
	my $t_uid = $1 if $to   =~ s{~(\w+)/}{};

	warn "send_file $f_uid $from -> $t_uid $to\n";

	$api->send_file( $f_uid => $from, $t_uid => $to );
});

=head2 rename_file ~u2001/old.txt#new.txt

=cut

$worker->register_function( rename_file => sub {
	my ($job) = @_;

	my $work = $job->arg;
	chomp $work;
	warn "# rename_file [$work]\n";

	my ( $from, $to ) = split(/#/,$work,2);
	my $login = $1 if $from =~ s{~(\w+)/}{};
	$api->rename_file( $login, $from, $to );
});

=head2 delete ~u2001/file_or_dir

=cut

$worker->register_function( delete => sub {
	my ($job) = @_;
	my $work = $job->arg;
	chomp $work;
	warn "# delete [$work]\n";

	my $login = $1 if $work =~ s{~(\w+)}{};
	$api->delete( $login, $work );

});

=head2 file_size ~u2001/foo.txt

=cut

$worker->register_function( file_size => sub {
	my ($job) = @_;
	my $work = $job->arg;
	chomp $work;
	warn "# file_size [$work]\n";

	my $login = $1 if $work =~ s{~(\w+)}{};
	$api->file_size( $login, $work );
});

=head2 user_usage u2001

=cut

$worker->register_function( user_usage => sub {
	my ($job) = @_;
	my $work = $job->arg;
	chomp $work;
	warn "# usage [$work]\n";
	my $usage = $api->usage( $work );
	return $usage->{_usage};
});

warn "$0 pid $$ waitng for jobs\n";

$worker->work while 1;

