#!/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 threads;
use threads::shared;
use Thread::Queue;
use IO::Socket;
use Proc::Daemon;
use Time::HiRes;

# Check perl for threads support
$Config{useithreads} or die "Recompile Perl with threads to run this program.";

# 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/commands.pm';
require $SELF_DIR . '/lib/control.pm';

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

#-----------------------------------------------------------------
my $postfix = "";
if (scalar(@ARGV) && $ARGV[0] =~ /^@(.*)/) {
    shift(@ARGV);
    $postfix = "_$1";
}

my $cfg_file = "mmm_mon$postfix.conf";
unless (-f "$SELF_DIR/etc/$cfg_file") {
    print "Error: Can't find monitoring system config ($cfg_file)!\n";
    print "\tLooks like you are trying to start mmm_control on wrong server or specified wrong cluster name!\n\n";
    exit(1);
}

# Read config file
print "Config file: $cfg_file\n";
our $config = ReadConfig($cfg_file);

# Create commands map
our $commands_map = {};
$commands_map->{ping} = \&PingCommand;
$commands_map->{show} = \&ShowCommand;
$commands_map->{set_online} = \&SetOnlineCommand;
$commands_map->{set_offline} = \&SetOfflineCommand;
$commands_map->{move_role} = \&MoveRoleCommand;
$commands_map->{failover_method} = \&SetFailoverMethod;

# Check params
if (scalar(@ARGV) < 1) {
    PrintUsage();
    exit(1);
}

my $command = lc($ARGV[0]);
chomp($command);

unless ($commands_map->{$command}) {
    print "Error: Invalid command name: $command!\n";
    PrintUsage();
    exit(1);
}

$commands_map->{$command}();

exit(0);

#-----------------------------------------------------------------
sub PrintUsage() {
    my @command_names = keys(%$commands_map);
    print "Usage: $0 <" . join('|', @command_names) . "> [..params..]\n\n";
}
