package Gruntmaster::Daemon::Base;

use 5.014000;
use strict;
use warnings;
use parent qw/Exporter/;
our @EXPORT_OK = qw/watch/;
our $VERSION = '0.001';

use Fcntl qw/O_WRONLY O_EXCL O_CREAT/;
use Linux::Inotify2;
use Log::Log4perl qw/get_logger/;

##################################################

sub process{
  my ($name, $dir, $cb) = @_;
  my $logger = get_logger;
  $logger->debug("Taking job $name...");
  if (sysopen my $file, "$dir/$name/pidfile", O_WRONLY | O_EXCL | O_CREAT){
	$logger->debug("Successfully taken job $name, executing callback");
	$cb->("$dir/$name");
  } else {
	$logger->debug("Job $name already taken");
  }
}

sub watch{
  my ($dir, $cb) = @_;
  for (<$dir/*>) {
	s,$dir/,,;
	process $_, $dir, $cb;
  }

  my $logger = Log::Log4perl->get_logger(__PACKAGE__);
  my $inotify = Linux::Inotify2->new or $logger->logdie("Unable to create Linux::Inotify2 object: $!");
  $inotify->watch($dir, IN_MOVED_TO, sub { process $_[0]->name, $dir, $cb }) or $logger->logdie("Error watching $dir: $!");
  1 while $inotify->poll;
  $logger->logdie("Inotify polling stopped: $!");
}

1
