#!/usr/bin/env perl

use strict;
use warnings FATAL => 'all';
use English qw( PROGRAM_NAME );
use Proc::Daemon;
use Log::Log4perl qw(:easy);
Log::Log4perl->easy_init($INFO);

# Define protocol version
use constant MMM_PROTOCOL_VERSION => 1;


# Include parts of the system
use MMM::Common::Angel;
use MMM::Common::Config;
use MMM::Common::Log;
use MMM::Common::PidFile;
use MMM::Agent::Agent;

chdir('/');
umask(0022);

MMM::Common::Log::init('mmm_agent_log.conf', 'mmmd_agent');

# Read configuration
our $config = new MMM::Common::Config::;
$config->read('mmm_agent');
$config->check('AGENT');

my $debug = $config->{debug};

MMM::Common::Log::debug() if ($debug);

our $agent	= new MMM::Agent::Agent::(
	protocol_version	=> 1,
	active_master		=> '',
	state				=> 'UNKNOWN'
);
$agent->from_config($config);

my $pidfilename = $config->{host}->{ $config->{this} }->{pid_path};
my $pidfile = new MMM::Common::PidFile:: $pidfilename;

# Check pid file
LOGDIE	"Can't run second copy of ", $PROGRAM_NAME	if ($pidfile->is_running());
WARN	"Unclean start - found stale pid file!"		if ($pidfile->exists());

unless ($debug) {
	# Go to background
	Proc::Daemon::Init();
	# Set umask again
	umask(0022);
	# Init logging again to re-open fds
	MMM::Common::Log::init('mmm_agent_log.conf', 'mmmd_agent');
}

# Init angel magic, which will restart us if we die unexpected
MMM::Common::Angel::Init($pidfile);

# Shutdown flag
our $shutdown = 0;

# Catch signals
$SIG{INT} = \&SignalHandler;
$SIG{TERM} = \&SignalHandler;
$SIG{QUIT} = \&SignalHandler;

$agent->main();

INFO 'END';
exit(0);

#-----------------------------------------------------------------
sub SignalHandler() {
	INFO "Signal received: exiting...";
	$shutdown = 1;
}
