#!/usr/bin/env perl

# Copyright (c) 2025, R. W. Rodolico
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
#    list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
#    this list of conditions and the following disclaimer in the documentation
#    and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Revision History:
# 2026-10-12 Copilot v1.0.0 r? main-flow tests for TESTING config, self-version overwrite, postRunScript, and JSON encoding

use strict;
use warnings;
use Test::More;
use lib './unix';
use File::Temp qw(tempdir tempfile);
use File::Path qw(make_path);
use YAML::Tiny;
use JSON::PP;

require './unix/sysinfo_client';

my $tempDir = tempdir(CLEANUP => 1);
my $sensorDir = "$tempDir/sensors";
my $scriptDir = "$tempDir/scripts";
make_path($sensorDir, $scriptDir);

my $allSysinfo = "$sensorDir/all_sysinfo";
open my $fhSensor, '>', $allSysinfo or die $!;
print {$fhSensor} "#!/usr/bin/env perl\n";
print {$fhSensor} "print \"software\\tsysinfo-client\\tversion\\tv3.7.1\\n\";\n";
print {$fhSensor} "exit 0;\n";
close($fhSensor);
chmod 0700, $allSysinfo;

my $configPath = "$tempDir/sysinfo_client.yaml";
my $configDoc = {
   'clientName' => 'Client Main Test',
   'hostname' => 'main-host.example',
   'serialNumber' => 'MAIN123',
   'UUID' => '550e8400e29b41d4a716446655440000',
   'moduleDirs' => [$sensorDir],
   'scriptDirs' => [$scriptDir],
   'transports' => {
      '1' => {
         'sendScript' => 'missing_transport',
         'name' => 'Missing',
      },
   },
   'logging' => {
      'log type' => 'cache',
      'log level' => 0,
   },
   'TESTING' => 0,
   'reportOutput' => "$tempDir/main-report.yaml",
   'postRunScript' => {
      'script name' => 'postrun_client_main_stub',
   },
};
YAML::Tiny->new($configDoc)->write($configPath);

my $postOutput = "$tempDir/postrun.out";
my $sourcePostScript = './unix/postrun_client_main_stub';
open my $fhPost, '>', $sourcePostScript or die $!;
print {$fhPost} "#!/usr/bin/env perl\n";
print {$fhPost} "open my \$out, '>', '$postOutput' or die \$!;\n";
print {$fhPost} "print {\$out} join('|', \$ARGV[0], (-e '/tmp/sysinfo.firstrun' ? 'present' : 'missing'));\n";
print {$fhPost} "close \$out;\n";
print {$fhPost} "exit 0;\n";
close($fhPost);
chmod 0700, $sourcePostScript;

my $scriptDirPost = "$scriptDir/postrun_client_main_stub";
open my $fhWrongPost, '>', $scriptDirPost or die $!;
print {$fhWrongPost} "#!/usr/bin/env perl\nopen my \$out, '>', '$postOutput' or die \$!; print {\$out} 'wrong-script-dir'; close \$out; exit 0;\n";
close($fhWrongPost);
chmod 0700, $scriptDirPost;

my $merged = mergeCLIOptions({
   'logging' => {
      'log type' => 'cache',
      'log level' => 0,
   },
   'TESTING' => 1,
}, {
   'test' => 0,
   'periodic' => 0,
});
is($merged->{'testing'}, 1, 'config TESTING enables testing mode even without -t');

my $jsonOut = hashToReportString({'system' => {'note' => 'café'}}, 'json');
unlike($jsonOut, qr/cafÃ©/, 'json output does not double-encode non-ASCII text');

unlink('/tmp/sysinfo.firstrun') if -e '/tmp/sysinfo.firstrun';
runPostRunScript($configDoc, $configPath);

ok(-f $postOutput, 'postRunScript executed');
open my $fhPostResult, '<', $postOutput or die $!;
my $postLine = do { local $/; <$fhPostResult> };
close($fhPostResult);
chomp $postLine;
is($postLine, "$configPath|missing", 'postRunScript uses sourceDir before scriptDirs');

open my $fhSrc, '<', './unix/sysinfo_client' or die $!;
my $sourceText = do { local $/; <$fhSrc> };
close($fhSrc);

like(
   $sourceText,
   qr/processSensors\(\$report, \$config, \$sensorEnv\);\s+\$report->\{'software'\}\{'sysinfo-client'\}\{'version'\} = \$VERSION->normal;/s,
   'self version assignment appears after processSensors call',
);

like(
   $sourceText,
   qr/unlink\(\$periodicOverrideFile\) if -e \$periodicOverrideFile;\s+runPostRunScript\(\$config, \$configPath\);/s,
   'periodic marker removal appears before postRunScript call',
);

unlink($sourcePostScript);

done_testing();
