#!/usr/bin/perl 
use strict;
use warnings;
use threads;
use threads::shared;
use Thread::Queue;
use Time::HiRes qw/sleep/;

use lib qw(libs);
use API::Config;
BEGIN { use lib $API::Config::Config->{'Website_libs'} }
use API::WarehouseOS::Daemon;
$| = 1;
warn sprintf "Warehouse OS on %s\n", $ECS::Config::c{warehouseOS}{host};


my $control = API::WarehouseOS::Daemon->new;
my $queue  = $control->queue;

my $handler = sub {
	print "Shutting Down..\n";
	$control->do_quit(1);
};

$SIG{$_} = $handler for qw/HUP TERM INT QUIT/;
$control->write_pid;


my $receive_thread = threads->create( sub {
	my ($queue) = @_;
	@_ = ();
	my $receiver = API::WarehouseOS::Daemon->new( queue => $queue );
	$SIG{KILL} = sub { # this gets the thread kill from the SIGALRM handler
		print "Shutting down receive from KILL\n";
		threads->exit;
	};
	$receiver->receive; 
}, $queue );

$SIG{ALRM} = sub {
	print "Shutting Down..(ALRM)\n";
	$control->do_quit(1) if $control;
	$receive_thread->kill('KILL')->detach if $receive_thread;
};

$control->send();
$control->eof();
$receive_thread->join if $receive_thread;
undef $receive_thread;
undef $control;
undef $queue;

