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

use Data::Dump qw(dump);
use File::Path qw(make_path remove_tree);

sub home_dir {
	my $login = shift;
	my ( undef, undef, $uid, $gid, undef, undef, $email, $dir, $shell ) = getpwnam $login;
	return $dir;
}

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

open(my $log, '>>', '/rsync1/s1/log/send_file.log');
select($log); $|++;

$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_dir = home_dir($1) if $from =~ s/~(\w+)//;
	my $t_dir = home_dir($1) if $to   =~ s/~(\w+)//;

	warn "send_file $f_dir $from -> $t_dir $to\n";

	my $t_basedir = $t_dir . $to;
	$t_basedir =~ s{/[^/]+$}{};
	make_path $t_basedir unless -d $t_basedir;
	link $f_dir . $from => $t_dir . $to;

	print "send#$work#", -s $t_dir.$to, "#$!\n";

	die "ERROR: $!" if $!;

	return "send_file $f_dir $from -> $t_dir $to";
});


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

	my $dir = home_dir($1) if $work =~ s/~(\w+)//;
	my $login = $1;
	my $full = $dir . $work;

	if ( -d $full ) {
		print "delete_tree#$work\n";
		warn "remove_tree $full\n";
		remove_tree $full;
	} else {
		print "delete_file#$work#", -s $full, "\n";
		warn "unlink $full\n";
		unlink $full;
	}
	if ( $! ) {
		warn "ERROR: $!";
		return "$full: $!\n";
	} else {
		return "$full: OK\n";
	}

});

warn "$0 pid $$ waitng for jobs\n";
$worker->work while 1;

