#!/usr/bin/perl
#
# vim: ts=4:noet
#
# sbotest (wrapper script)
# sbotools-based reverse dependency build tester
#
# author: K. Eugene Carlson <kvngncrlsn@gmail.com>
# license: MIT License

use 5.16.0;
use strict;
use warnings;

my $util_pm = "/usr/share/perl5/vendor_perl/SBO/Lib/Util.pm";
unless (-f $util_pm) {
	say "sbotools must be installed. Exiting.";
	exit 1;
}

# the following ENV variables must be set first

# if the user sets SBOTEST_CONF_DIR, use that
my $test_conf_req = $ENV{SBOTEST_CONF_DIR};
my $test_conf_dir = defined $test_conf_req ? $test_conf_req : "/etc/sbotest";

# use the sbotest configuration directory and defaults
$ENV{SBOTOOLS_CONF_DIR} = $test_conf_dir;
$ENV{SBOTEST_MODE} = 1;

my ($config, $find, $hints, $pull, @SVARG);
unless (@ARGV) {
	system("/usr/libexec/sbotest/test --help");
	exit 1;
}
$config = 1 if $ARGV[0] eq 'config';
$pull = 1 if $ARGV[0] eq 'pull';
$hints = 1 if $ARGV[0] eq 'hints';
$find = 1 if $ARGV[0] eq 'find';

for my $arg (@ARGV) {
	next if $arg eq 'config' or $arg eq 'hints' or $arg eq 'pull' or $arg eq 'find';
	push @SVARG, $arg;
}

my $string = "#% SBOTEST V1.2.1 COMPAT %concluded %\n";
my $fh;
unless (open $fh, '<', $util_pm) { say "Failed to open $util_pm for reading."; exit 6; }
my $is_compatible;
for my $line (<$fh>) {
	if ($line eq $string) { $is_compatible = 1; last; }
}
close $fh;
unless ($is_compatible) {
	say "This version of sbotools is incompatible with this version of sbotest.\nUpgrade sbotools to at least 20251212-e74bc3f.";
	exit 1;
}

if ($config) {
	if (@SVARG) {
		system('/usr/sbin/sboconfig', @SVARG);
	} else {
		system('/usr/sbin/sboconfig --help');
	}
} elsif ($hints) {
	system('/usr/sbin/sbohints', @SVARG);
} elsif ($find) {
	system('/usr/sbin/sbofind', @SVARG);
} elsif ($pull) {
	system('/usr/libexec/sbotest/pull', @SVARG);
} else {
	system('/usr/libexec/sbotest/test', @SVARG);
}
