#!/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 Clone qw(clone);

use Data::Validate::Domain qw(is_domain);
use Data::Validate::IP qw(is_ipv4);
use Net::IP;
use File::Temp qw(tempfile);

use perfSONAR_PS::MeshConfig::Utils qw(load_mesh build_json);

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

my ( $status, $res );

my $INPUT = '-';
my $OUTPUT = '-';
my $LOGGER_CONF;
my $DEBUGFLAG;
my $SKIP_VALIDATION;
my $RESOLVE_INCLUDES;
my $HELP;

$status = GetOptions(
    'input=s'  => \$INPUT,
    'output=s' => \$OUTPUT,
    'logger=s'  => \$LOGGER_CONF,
    'skip-validation' => \$SKIP_VALIDATION,
    'resolve-includes' => \$RESOLVE_INCLUDES,
    '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 %configuration;

if ($INPUT eq "-") {
    my $config = "";
    while(<>) {
        $config .= $_;
    }
    %configuration = Config::General->new(-String => $config)->getall;
}
else {
    %configuration = Config::General->new($INPUT)->getall;
}

my ($json_status, $result) = build_json(configuration => \%configuration, 
                                    skip_validation => $SKIP_VALIDATION, 
                                    resolve_includes => $RESOLVE_INCLUDES);
if($json_status < 0){
    print $result;
    exit(-1);
}

if ($OUTPUT eq "-") {
    print JSON->new->pretty(1)->encode($result);
}
else {
    open(OUTPUT, ">$OUTPUT");
    print OUTPUT JSON->new->pretty(1)->encode($result);
    close(OUTPUT);
}

exit 0;

