#!/usr/bin/env perl

=head1 NAME

check_latex - Test the LaTeX installation to see that it contains the necessary
packages for webwork2 hardcopy generation.

=cut

use strict;
use warnings;
use feature 'say';

BEGIN {
	use Mojo::File qw(curfile);
	use YAML::XS qw(LoadFile);
	use Env qw(WEBWORK_ROOT PG_ROOT);

	$WEBWORK_ROOT = curfile->dirname->dirname->to_string;

	# Load the configuration file to obtain the PG root directory.
	my $config_file = "$WEBWORK_ROOT/conf/webwork2.mojolicious.yml";
	$config_file = "$WEBWORK_ROOT/conf/webwork2.mojolicious.dist.yml" unless -e $config_file;
	my $config = LoadFile($config_file);

	$PG_ROOT = $config->{pg_dir};
}

use File::Temp qw(tempdir);
use File::Path qw(rmtree);
use String::ShellQuote;

use lib "$ENV{WEBWORK_ROOT}/lib";

use WeBWorK::CourseEnvironment;

my $ce = WeBWorK::CourseEnvironment->new({ webwork_dir => $ENV{WEBWORK_ROOT} });

my $temp_dir = eval { tempdir('check_latex_XXXXXXXX') };

die $@ if $@;

my $latex_cmd =
	"cd $temp_dir && "
	. "TEXINPUTS=$ENV{WEBWORK_ROOT}/bin:"
	. shell_quote($ce->{webworkDirs}{assetsTex}) . ':'
	. shell_quote($ce->{pg}{directories}{assetsTex}) . ': '
	. $ce->{externalPrograms}{latex2pdf}
	. ' -interaction nonstopmode check_latex_article.tex > check_latex.nfo 2>&1 &&'
	. "TEXINPUTS=$ENV{WEBWORK_ROOT}/bin:"
	. shell_quote($ce->{webworkDirs}{assetsTex}) . ':'
	. shell_quote($ce->{pg}{directories}{assetsTex}) . ': '
	. $ce->{externalPrograms}{latex2pdf}
	. ' -interaction nonstopmode check_latex_exam.tex >> check_latex.nfo 2>&1';

if ((system $latex_cmd) >> 8) {
	if (open(my $fh, '<', "$temp_dir/check_latex.nfo")) {
		local $/;
		my $nfo = <$fh>;
		close($fh);

		say $nfo;
	}
	say 'Compilation Failure: Examine the latex output above to see what went wrong.';
	say "You may also examine $temp_dir/check_latex.log and $temp_dir/check_latex.aux.";
} else {
	say 'Compilation Success!';
	rmtree $temp_dir;
}
