#!/usr/local/cpanel/3rdparty/bin/perl -w

#                                      Copyright 2024 WebPros International, LLC
#                                                           All rights reserved.
# copyright@cpanel.net                                         http://cpanel.net
# This code is subject to the cPanel license. Unauthorized copying is prohibited.

use v5.36;
use Test::More;
use Test::Exception;
use Test::Deep;
use File::Path qw(make_path);
use autodie;

use experimental 'builtin';

use Whostmgr::360Monitoring::Util ();
use Whostmgr::360Monitoring::Agent;

use constant TEMP_FILE => '/tmp/stupidini.ini';

# Write file
{
    my $ini_file_content = <<~ "_INI_";
    [DEFAULT]
    max_data_span = 60
    max_data_age = 600
    logging_level = 30
    threads = 100
    interval = 60
    _INI_
    open my $fh, ">", TEMP_FILE;
    print $fh $ini_file_content;
}

# Read file check reflow
{
    my $agent = Whostmgr::360Monitoring::Agent::load_from_file(TEMP_FILE);

    my $reflow_ini = <<~_INI_;
        # --------------------------------------------------------
        # Warning: DO NOT EDIT THIS FILE.
        # --------------------------------------------------------
        # Description: agent360.ini for cPanel & WHM server. This
        # configuration file is generated automatically by the
        # cpanel-monitoring-plugin and used in conjunction with
        # the 360 Monitoring.
        # --------------------------------------------------------
        [DEFAULT]
        interval=60

        [agent]
        interval=60
        logging_level=30
        max_data_age=600
        max_data_span=60

        [data]
        interval=60

        [execution]
        interval=60
        threads=100
        _INI_

    is( $agent->to_INI, $reflow_ini, 'loading_from disk results in a different ini' );
}

# Ensure disk and memory can both reflow
{
    # Not reflowed on disk
    my $agent_disk = Whostmgr::360Monitoring::Agent::load_from_file(TEMP_FILE);

    # Not reflowed in mem
    my $ini_file_contents = <<~_INI_;
    [DEFAULT]
    max_data_span = 60
    max_data_age = 600
    logging_level = 30
    threads = 100
    interval = 60
    _INI_

    my $agent_mem = Whostmgr::360Monitoring::Agent::from_INI( \$ini_file_contents );
    $agent_mem->save_to_file(TEMP_FILE);

    my $agent_disk_reflow = Whostmgr::360Monitoring::Agent::load_from_file(TEMP_FILE);

    is( $agent_disk->to_INI,        $agent_mem->to_INI, 'load_from_file and from_INI both reflow' );
    is( $agent_disk_reflow->to_INI, $agent_mem->to_INI, 'reading reflow from disk also works' );

}

done_testing();

1;
