#!/usr/bin/env perl

# Revision History:
# 2026-10-25 Claude v1.0.0 bug 212: configure is a wrapper around dsEdit; tests use a stub dsEdit

use strict;
use warnings;
use File::Copy qw(copy);
use File::Path qw(make_path);
use File::Temp qw(tempdir);
use Test::More;

my $tmp = tempdir(CLEANUP => 1);
make_path("$tmp/dataserialization");
copy('unix/configure', "$tmp/configure") or die $!;
copy("unix/$_", "$tmp/$_") or die $! foreach qw(sysinfoconf.pm library.pm);

# runs the copied configure with the given parameters, returns (exit code, combined output)
sub runConfigure {
   my @args = @_;
   my $pid = open(my $fh, '-|') // die $!;
   if (!$pid) {
      open(STDERR, '>&', \*STDOUT);
      exec { $^X } $^X, "$tmp/configure", @args or die $!;
   }
   local $/;
   my $out = <$fh>;
   close($fh);
   return ($? >> 8, $out);
}

# a stand-in dsEdit that prints each parameter on its own line
sub writeStub {
   open(my $fh, '>', "$tmp/dataserialization/dsEdit") or die $!;
   print $fh "#!/usr/bin/env perl\nprint \"ARG[\$_]\\n\" foreach \@ARGV;\nexit 0;\n";
   close($fh);
}

my ($rc, $out) = runConfigure('x.yaml');
is($rc, 2, 'missing dsEdit exits 2');
like($out, qr/dsEdit not found/, 'missing dsEdit is explained');

writeStub();

($rc, $out) = runConfigure('-a', 'tags[]:prod', '-d', 'old.key', 'my file.yaml');
is($rc, 0, 'file given: runs dsEdit');
is($out, "ARG[-a]\nARG[tags[]:prod]\nARG[-d]\nARG[old.key]\nARG[my file.yaml]\n", 'parameters pass through unchanged, spaces intact, nothing added');

($rc, $out) = runConfigure('--outfile', 'out.json', 'in.yaml');
is($out, "ARG[--outfile]\nARG[out.json]\nARG[in.yaml]\n", '--outfile value is not the file; given file kept');

($rc, $out) = runConfigure('--addentry=a.b:c', 'in.yaml');
is($out, "ARG[--addentry=a.b:c]\nARG[in.yaml]\n", '--opt=value form passes through');

($rc, $out) = runConfigure('-f', 'ini', '--delimiter', ':', 'in.conf');
is($out, "ARG[-f]\nARG[ini]\nARG[--delimiter]\nARG[:]\nARG[in.conf]\n", 'format and delimiter values are not mistaken for the file');

($rc, $out) = runConfigure('--help');
is($out, "ARG[--help]\n", '--help passes through with no file added');

($rc, $out) = runConfigure('-a', 'k:v', '--', '-odd.yaml');
is($out, "ARG[-a]\nARG[k:v]\nARG[--]\nARG[-odd.yaml]\n", 'file after -- counts as a file');

# with no file given the wrapper adds the config file from the normal search, or fails clearly
SKIP: {
   skip 'a real client config exists on this host', 3
      if grep { -f "$_/sysinfo_client.yaml" } ('/etc/camp/sysinfo_client', '/usr/local/etc/camp/sysinfo_client');

   ($rc, $out) = runConfigure();
   is($rc, 2, 'no file and no config: exits 2');
   like($out, qr/config file .*sysinfo_client\.yaml does not exist/, 'names the config file it looked for');

   ($rc, $out) = runConfigure('-a', 'k:v');
   is($rc, 2, 'option value is not mistaken for a file');
}

done_testing();
