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

use Data::Dump qw(dump);

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

die "missing ZSLICE from env" unless $ENV{ZSLICE};

sub zfs {
	my ($fmt,$job) = @_;
	my $work = $job->arg;
	chomp $work;

	my $zfs = sprintf $fmt, split(/ /,$work);
	warn "# zfs_get [$work] -> $zfs\n";

	my $v = `$zfs`;
	chomp $v;

	warn "# $work = $v\n";

	return $v;
}

my $name = $ENV{ZSLICE};
$name =~ s/\W+/_/g;

$worker->register_function( $name . '_quota_get' => sub {
	my $used = zfs( "zfs get -H -p -o value userused\@%s $ENV{ZSLICE}" => $_[0] );
	my $quota = zfs( "zfs get -H -p -o value userquota\@%s $ENV{ZSLICE}" => $_[0] );
	return "$used $quota";
} );

$worker->register_function( $name . '_quota_set' => sub { zfs( 
"zfs set userquota\@%s=%s $ENV{ZSLICE}" => $_[0]
) } );

warn "$0 $name pid $$ waitng for jobs ZFS slice $ENV{ZSLICE}\n";
$worker->work while 1;

