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

use Transmission::Client;
use JSON::XS;
use Data::Dump qw(dump);
use autodie;

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');

my $tc = Transmission::Client->new( autodie => 1 );

my $j = JSON::XS->new;
$j->allow_blessed(1);
$j->convert_blessed(0);

use TokyoCabinet;

my $name = $ENV{ZSLICE} || die "need ZSLICE";
my $torrent_dir = "/$name/torrent";
$name =~ s/\W+/_/g;

$worker->register_function( $name . '_torrent_list' => sub {
	my ($job) = @_;
	my @cols = split(/\s+/,$job->arg);
	@cols = qw( id name seeders leechers ) unless @cols;
	my @list;	
	for my $torrent ($tc->read_torrents) {
		warn "## torrent = ",dump($torrent);
		my $hash;
		$hash->{$_} = $torrent->$_ foreach @cols;
		push @list, $hash;
	}
	warn "# torrent_list = ",dump( \@list );
	return $j->encode( \@list );
} );

$worker->register_function( $name . '_torrent_download' => sub {
	my $work = $_[0]->arg;
	chomp $work;
	warn "# torrent_download [$work]\n";
	
	my $user = $1 if $work =~ s{~(\w+)/}{};
	my $path = $work;

	my $dir = (getpwnam($user))[7] || die "no user $user";

	my $to_dir = "$torrent_dir/download/$user";
	if ( ! -e $to_dir ) {
		mkdir $to_dir;
		# fix perm
		my ($uid,$gid) = (stat($torrent_dir))[4,5];
		chown $uid, $gid, $to_dir;
	}

	$tc->add( filename => "$dir/$path", 'download-dir' => $to_dir );

	return $to_dir;
} );

$worker->register_function( $name . '_torrent_share' => sub {
	my $work = $_[0]->arg;
	chomp $work;
	warn "# torrent_share [$work]\n";
	
	my $user = $1 if $work =~ s{~(\w+)/}{};
	my $path = $work;

	my $dir = (getpwnam($user))[7] || die "no user $user";
	my $md5_path = "$dir/.md5";
	my %h;
	tie %h, "TokyoCabinet::HDB", $md5_path || die "$md5_path: $!";
	my $md5 = $h{$path} || die "can't find $path in $md5_path";
	untie %h;

	warn "# $md5 $path";

	if ( ! -e "$torrent_dir/download/$md5" ) {
		symlink "/rsync1/s1/md5/$md5", "$torrent_dir/download/$md5"; # FIXME slice path
		warn "# created $torrent_dir/download/$md5";
	}

	if ( ! -e "$torrent_dir/md5/$md5.torrent" ) {
		my $tracker = "http://213.186.16.27:6502/announce"; # FIXME
		system "mktorrent --announce $tracker --no-date --verbose --output $torrent_dir/md5/$md5.torrent $torrent_dir/download/$md5";

	}

	symlink "$torrent_dir/md5/$md5.torrent", "$dir/$path.torrent" unless -e "$dir/$path.torrent";

	$tc->add( filename => "$torrent_dir/md5/$md5.torrent" );

	return "$dir/$path";
} );

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

