#!/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-11 Copilot v1.0.0 r? initial sensor runtime tests
# 2026-10-12 Copilot v1.1.0 r? timeout grandchild cleanup and non-executable discovery checks

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

require './unix/sysinfo_client';

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

my $markerFile = "$tempDir/timeout-marker";

my %scripts = (
   'ok_sensor' => "#!/usr/bin/env perl\nprint \"system\\thostname\\thost.example\\n\"; exit 0;\n",
   'wrongos_sensor' => "#!/usr/bin/env perl\nprint STDERR \"unsupported os\\n\"; exit 1;\n",
   'na_sensor' => "#!/usr/bin/env perl\nprint STDERR \"smartctl not found\\n\"; exit 2;\n",
   'notdue_sensor' => "#!/usr/bin/env perl\nprint STDERR \"not due\\n\"; exit 3;\n",
   'error_sensor' => "#!/usr/bin/env perl\nprint STDERR \"broken\\n\"; exit 4;\n",
   'silent_na_sensor' => "#!/usr/bin/env perl\nexit 2;\n",
   'die_sensor' => "#!/usr/bin/env perl\ndie \"crash\\n\";\n",
   'timeout_sensor' => "#!/usr/bin/env perl\nsleep 5; print \"system\\tlate\\t1\\n\"; exit 0;\n",
   'timeout_child_sensor' => "#!/usr/bin/env perl\nmy \$marker = '$markerFile';\nmy \$pid = fork();\nif (\$pid == 0) { \$SIG{TERM} = 'IGNORE'; sleep 10; open my \$m, '>', \$marker or die \$!; print {\$m} 'late'; close \$m; exit 0; }\nsleep 20; exit 0;\n",
   'emptykey_sensor' => "#!/usr/bin/env perl\nprint \"system\\t\\tvalue\\n\"; exit 0;\n",
   'garbage_sensor' => "#!/usr/bin/env perl\nprint \"garbage\\n\"; exit 0;\n",
);

foreach my $name (keys %scripts) {
   my $path = "$sensorDir/$name";
   open my $fh, '>', $path or die $!;
   print {$fh} $scripts{$name};
   close($fh);
   chmod 0700, $path;
}

my $nonExecFile = "$sensorDir/README";
open my $fhReadme, '>', $nonExecFile or die $!;
print {$fhReadme} "not executable sensor file\n";
close($fhReadme);
chmod 0600, $nonExecFile;

my $report = {
   'sysinfo' => {
      'sensors' => {},
   },
};

my $config = {
   'moduleDirs' => [$sensorDir],
   'testing' => 1,
   'sensorTimeout' => 2,
   'logging' => {
      'log type' => 'cache',
      'log level' => 0,
   },
};

my $env = {
   'SYSINFO_CONFIGURED_UUID' => 'confuuid',
   'SYSINFO_CONFIGURED_SERIAL' => 'confserial',
   'SYSINFO_SERVERINFO_UUID' => 'srvuuid',
   'SYSINFO_SERVERINFO_SERIAL' => 'srvserial',
   'SYSINFO_PERIODIC' => 1,
};

processSensors($report, $config, $env);

is($report->{'sysinfo'}{'sensors'}{'ok_sensor'}{'status'}, 'ok', 'exit 0 sensor marked ok');
is($report->{'sysinfo'}{'sensors'}{'wrongos_sensor'}{'status'}, 'wrong_os', 'exit 1 sensor marked wrong_os');
is($report->{'sysinfo'}{'sensors'}{'na_sensor'}{'status'}, 'not_applicable', 'exit 2 sensor marked not_applicable');
is($report->{'sysinfo'}{'sensors'}{'na_sensor'}{'message'}, 'smartctl not found', 'exit 2 reason kept as message');
is($report->{'sysinfo'}{'sensors'}{'silent_na_sensor'}{'status'}, 'not_applicable', 'exit 2 without STDERR still not_applicable');
ok(!exists $report->{'sysinfo'}{'sensors'}{'silent_na_sensor'}{'message'}, 'no message when STDERR empty');
is($report->{'sysinfo'}{'sensors'}{'notdue_sensor'}{'status'}, 'not_due', 'exit 3 sensor marked not_due');
is($report->{'sysinfo'}{'sensors'}{'error_sensor'}{'status'}, 'error', 'exit 4 sensor marked error');
is($report->{'sysinfo'}{'sensors'}{'die_sensor'}{'status'}, 'error', 'die sensor marked error');
is($report->{'sysinfo'}{'sensors'}{'timeout_sensor'}{'status'}, 'timeout', 'long-running sensor marked timeout');
is($report->{'sysinfo'}{'sensors'}{'timeout_child_sensor'}{'status'}, 'timeout', 'sensor with TERM-ignoring child marked timeout');
ok($report->{'sysinfo'}{'sensors'}{'emptykey_sensor'}{'rejected_lines'} >= 1, 'empty-key line counted as rejected');
ok($report->{'sysinfo'}{'sensors'}{'garbage_sensor'}{'rejected_lines'} >= 1, 'garbage line counted as rejected');
ok(!exists($report->{'sysinfo'}{'sensors'}{'README'}), 'non-executable file is skipped and not tracked as sensor status');

is($report->{'system'}{'hostname'}, 'host.example', 'valid sensor data merged into report');

sleep 12;
ok(!-e $markerFile, 'timeout cleanup kills process group and prevents child marker write');

done_testing();
