The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.
#!/usr/bin/env perl

use strict;
use warnings;

our $home;

BEGIN {
  use FindBin;
  FindBin::again();

  my $me = File::Spec->catfile($FindBin::RealBin, $FindBin::RealScript);
  my $uid = (stat($me))[4] || 0;

  $home = ($ENV{NETDISCO_HOME} || (getpwuid($uid))[7] || $ENV{HOME});

  # try to find a localenv if one isn't already in place.
  if (!exists $ENV{PERL_LOCAL_LIB_ROOT}) {
      use File::Spec;
      my $localenv = File::Spec->catfile($FindBin::Bin, 'localenv');
      exec($localenv, $0, @ARGV) if -f $localenv;
      $localenv = File::Spec->catfile($home, 'perl5', 'bin', 'localenv');
      exec($localenv, $0, @ARGV) if -f $localenv;

      die "Sorry, can't find libs required for App::Netdisco.\n"
        if !exists $ENV{PERLBREW_PERL};
  }
}

BEGIN {
  use Path::Class;

  # stuff useful locations into @INC and $PATH
  unshift @INC,
    dir($FindBin::RealBin)->parent->subdir('lib')->stringify,
    dir($FindBin::RealBin, 'lib')->stringify;

  use Config;
  $ENV{PATH} = $FindBin::RealBin . $Config{path_sep} . $ENV{PATH};
}

use Daemon::Control;
use Filesys::Notify::Simple;

use App::Netdisco::Environment;
my $config = ($ENV{PLACK_ENV} || $ENV{DANCER_ENVIRONMENT}) .'.yml';

my $netdisco = file($FindBin::RealBin, 'netdisco-daemon-fg');
my @args = (scalar @ARGV > 1 ? @ARGV[1 .. $#ARGV] : ());

my $log_dir = dir($home, 'logs');
mkdir $log_dir if ! -d $log_dir;

my $uid = (stat($netdisco->stringify))[4] || 0;
my $gid = (stat($netdisco->stringify))[5] || 0;

Daemon::Control->new({
  name => 'Netdisco Daemon',
  program  => \&restarter,
  program_args => [@args],
  pid_file => file($home, 'netdisco-daemon.pid'),
  stderr_file => file($log_dir, 'netdisco-daemon.log'),
  stdout_file => file($log_dir, 'netdisco-daemon.log'),
  redirect_before_fork => 0,
  uid => $uid, gid => $gid,
})->run;

# the guts of this are borrowed from Plack::Loader::Restarter - many thanks!!

sub restarter {
  my ($daemon, @program_args) = @_;

  my $child = fork_and_start($daemon, @program_args);
  exit(1) unless $child;

  my $watcher = Filesys::Notify::Simple->new([$ENV{DANCER_ENVDIR}]);
  warn "config watcher: watching $ENV{DANCER_ENVDIR} for updates.\n";

  local $SIG{TERM} = sub { signal_child('TERM', $child); exit(0); };

  while (1) {
      my @restart;

      # this is blocking
      $watcher->wait(sub {
          my @events = @_;
          @events = grep {file($_->{path})->basename eq $config} @events;
          return unless @events;
          @restart = @events;
      });

      next unless @restart;
      warn "-- $_->{path} updated.\n" for @restart;

      signal_child('TERM', $child);
      $child = fork_and_start($daemon, @program_args);
      exit(1) unless $child;
  }
}

sub fork_and_start {
  my ($daemon, @daemon_args) = @_;
  my $pid = fork;
  die "Can't fork: $!" unless defined $pid;

  if ($pid == 0) { # child
      $daemon->redirect_filehandles;
      exec( $netdisco->stringify, @daemon_args );
  }
  else {
      return $pid;
  }
}

sub signal_child {
  my ($signal, $pid) = @_;
  return unless $signal and $pid;
  warn "config watcher: sending $signal to the server (pid:$pid)...\n";
  kill $signal => $pid;
  waitpid($pid, 0);
}

=head1 NAME

netdisco-daemon - Job Control Daemon for Netdisco

=head1 SEE ALSO

=over 4

=item *

L<App::Netdisco>

=back

=cut