#!/usr/bin/perl

use strict;
use warnings;

use FindBin qw($RealBin);
use lib "$RealBin/../lib";

use Config::General;
use File::Path;
use Getopt::Long;
use JSON;
use Log::Log4perl qw(:easy);

use perfSONAR_PS::MeshConfig::GUIAgent;

Log::Log4perl->easy_init($DEBUG);

my $CONFIG_FILE = "$RealBin/../etc/gui_agent_configuration.conf";
my $LOGGER_CONF;
my $DEBUGFLAG;
my $HELP;

my ( $status, $res );

$status = GetOptions(
    'config=s'  => \$CONFIG_FILE,
    'logger=s'  => \$LOGGER_CONF,
    'verbose'   => \$DEBUGFLAG,
    'help'      => \$HELP
);

my $logger;
unless ( $LOGGER_CONF ) {
    use Log::Log4perl qw(:easy);

    my $output_level = $INFO;
    if ( $DEBUGFLAG ) {
        $output_level = $DEBUG;
    }

    my %logger_opts = (
        level  => $output_level,
        layout => '%d (%P) %p> %F{1}:%L %M - %m%n',
    );

    Log::Log4perl->easy_init( \%logger_opts );
}
else {
    use Log::Log4perl qw(get_logger :levels);

    Log::Log4perl->init( $LOGGER_CONF );
}

$logger = get_logger( "perfSONAR_PS" );
$logger->level( $DEBUG ) if $DEBUGFLAG;

my %conf = Config::General->new( $CONFIG_FILE )->getall();

my $admin_emails;
if ($conf{admin_email}) {
    unless (ref($conf{admin_email}) eq "ARRAY") {
        $conf{admin_email} = [ $conf{admin_email} ];
    }
}

unless (ref($conf{mesh}) eq "ARRAY") {
    $conf{mesh} = [ $conf{mesh} ];
}

my $agent = perfSONAR_PS::MeshConfig::GUIAgent->new();
$agent->init({
        meshes               => $conf{mesh},
        maddash_yaml         => $conf{maddash_yaml},
        maddash_options      => $conf{maddash_options},
        use_toolkit          => $conf{use_toolkit},
        from_address         => $conf{email_from_address},
        restart_services     => $conf{restart_services},
        administrator_emails => $conf{admin_email},
        send_error_emails    => $conf{send_error_emails},
        send_error_emails_to_mesh => $conf{send_error_emails_to_mesh},
});

$agent->run();
