#!/usr/bin/env perl

use strict;
use warnings;

use Getopt::Std;

use Gearman::XS qw(:constants);
use Gearman::XS::Worker;

my %opts;
if (!getopts('h:p', \%opts)) {
    usage();
    exit(1);
}

my $host	= $opts{h}	|| '';
my $port	= $opts{p}	|| 0;

my $worker = new Gearman::XS::Worker;

my $ret = $worker->add_server($host, $port);
if ($ret != GEARMAN_SUCCESS) {
    printf(STDERR "%s\n", $worker->error());
    exit(1);
}

$ret = $worker->add_function("make_sandbox", 0, \&make_sandbox, 0);
if ($ret != GEARMAN_SUCCESS) {
    printf(STDERR "%s\n", $worker->error());
}

while (1) {
    my $ret = $worker->work();
    if ($ret != GEARMAN_SUCCESS) {
    	printf(STDERR "%s\n", $worker->error());
    }
}

sub usage {
    printf("\nusage: %s [-h <host>] [-p <port>]\n", $0);
    printf("\t-h <host>  - job server host\n");
    printf("\t-p <port>  - job server port\n");
}

sub make_sandbox {
    my ($job, $options) = @_;

    my $command		= $job->workload();
    chomp $command;
    print STDERR "<$command>n";
    my $result = qx(make_sandbox $command) ;
    # my $result = qx(perl -le 'print "PERL IS OK"') ;
    if ($?) {
        print $result, "\n";
        return "Error ($!)\n";
    }
    else {
        return "ok\n"
    }
}

exit;