#!/usr/bin/perl
# Copyright 2026 Juan Manuel Méndez Rey <juan.mendezr@proton.me>
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.

# autopkgtest for packages built with scala-debian-helper: run from the source tree, it
# loads every class of each installed jar of debian/scala-build with the
# class path of its standard library and Classpath entries (Smoke.java).
# Usage: smoke-test [--root DIR]   (DIR: where the packages are unpacked,
#                                   instead of / ; for testing scala-debian-helper itself)
use strict;
use warnings;
use File::Temp;
use Debian::DhScala qw(
	read_config compiler_for pom_closure find_earlier_stanza group_path $JAVA_DIR $MAVEN_REPO
);

my $root = '';
if (@ARGV >= 2 && $ARGV[0] eq '--root') {
	(undef, $root) = splice(@ARGV, 0, 2);
}
my $smoke = $ENV{DH_SCALA_SMOKE_JAVA} // '/usr/share/scala-debian-helper/Smoke.java';
my $java  = ($ENV{JAVA_HOME} // '/usr/lib/jvm/default-java') . '/bin/java';
my $repo  = "$root$MAVEN_REPO";

my (%built, %cps, $bad);
for my $s (read_config()) {
	$built{ $s->{id} } = $s;
	next unless $s->{install};
	my $jar = "$root$JAVA_DIR/$s->{jar_name}.jar";
	die "smoke-test: $jar is not installed (package $s->{package})\n" unless -e $jar;
	# the standard library installed, else under --root
	my @cp = ($jar, map { -e $_ ? $_ : "$root$_" } @{ compiler_for($s->{binver})->{stdlib} });
	for my $e (@{ $s->{classpath} }) {
		if ($e =~ /^\@(.+)$/) {
			my $dep = find_earlier_stanza($s, $1, \%built)
			  // die "smoke-test: $s->{id}: Classpath $e is not an earlier stanza\n";
			push @cp, "$root$JAVA_DIR/$dep->{jar_name}.jar",
			  @{ $cps{ $dep->{id} } // [] };
		} elsif ($e =~ m{^/}) {
			push @cp, $e;
		} else {
			my ($g, $a, $v) = split /:/, $e;
			$v //= 'debian';
			# installed, else under --root
			my $path = group_path($g) . "/$a/$v/$a-$v.jar";
			my $r    = -e "$MAVEN_REPO/$path" ? $MAVEN_REPO : $repo;
			my $p    = "$r/$path";
			# and what it needs at run time, from the installed POMs
			push @cp, $p, map { $_->{path} } pom_closure($r, $g, $a, $v);
		}
	}
	# each jar once: the class paths of earlier stanzas repeat their
	# dependencies, and a large package goes past the length of an argument
	my %seen;
	@cp = grep { !$seen{$_}++ } @cp;
	$cps{ $s->{id} } = [@cp[1 .. $#cp]];
	print "== $s->{id} ($s->{package})\n";
	# the class path in an argument file, which java reads itself
	my $args = File::Temp->new;
	print {$args} "-cp\n", join(':', @cp), "\n";
	close $args or die "smoke-test: $args: $!\n";
	system($java, '@' . $args->filename, $smoke, $jar) == 0 or $bad = 1;
}
exit($bad ? 1 : 0);
