#!/usr/bin/env perl

# Use mandatory external modules
use strict;
use Cwd;
use File::Basename;
use Data::Dumper;
use POSIX;
use Config;
use Getopt::Long;
use IO::Socket;
use Proc::Daemon;
use Time::HiRes;

# Determine installation dir name
our $SELF_DIR = dirname(dirname(Cwd::abs_path(__FILE__)));

# Include parts of the system
require $SELF_DIR . '/lib/version.pm';
require $SELF_DIR . '/lib/config.pm';
require $SELF_DIR . '/lib/log.pm';
require $SELF_DIR . '/lib/agent_commands.pm';
require $SELF_DIR . '/lib/ifconfig.pm';

#-----------------------------------------------------------------
# Say hello
PrintVersion();

#-----------------------------------------------------------------
# Read config file
our $config = ReadConfig("mmm_agent.conf");

# We need to know how previous session has been finished
our $unclean_start = CheckPidFile();

# Go to background
Proc::Daemon::Init if ($config->{debug} =~ /^(off|no|0)$/i);
CreatePidFile();

# Shutdown flag
our $shutdown = 0;

# Start time to calculate uptime
our $start_time = time();

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

#-----------------------------------------------------------------
# Initialize server status
our $server_version = -1;
our $server_state = 'UNKNOWN';
our $server_roles = ();
our $active_master = "";

# Start command handler
CommandMain();

# Delete pid file and update status file
unlink($config->{pid_path});

exit(0);

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