use alienfile;

requires 'File::Which';

# Probe for these tools by default in addition to the library. This can be
# overridden by setting `ALIEN_DJVULIBRE_PROBE_TOOLS`:
#
#   - Set ALIEN_DJVULIBRE_PROBE_TOOLS=0 to disable probe for tools.
#   - Set ALIEN_DJVULIBRE_PROBE_TOOLS to space-delimited list of alternative
#     tools to probe.
my @DEFAULT_PROBE_TOOLS = qw{ddjvu c44 djvm};

my @should_probe_tools = exists $ENV{ALIEN_DJVULIBRE_PROBE_TOOLS}
	? ( $ENV{ALIEN_DJVULIBRE_PROBE_TOOLS} ne '0'
		? split(' ', $ENV{ALIEN_DJVULIBRE_PROBE_TOOLS})
		: ()
	)
	: @DEFAULT_PROBE_TOOLS;

meta->around_hook( probe => sub {
	my $orig = shift;
	my ($build) = @_;
	my $install_type = $orig->(@_);

	return $install_type unless @should_probe_tools;

	if( $install_type eq 'system' ) {
		my @missing_tools = grep { ! File::Which::which($_) } @should_probe_tools;
		if( ! @missing_tools ) {
			return 'system';
		} else {
			$build->log("Missing tools [ @missing_tools ] requires share install");
			return 'share';
		}
	}

	return $install_type;
});
plugin 'PkgConfig' => 'ddjvuapi';

share {
	requires 'ExtUtils::CppGuess' => '0.13';
	plugin 'Decode::SourceForge';
	start_url 'https://sourceforge.net/projects/djvu/files/DjVuLibre/3.5.28/';
	plugin 'Download' => (
		filter => qr/^djvulibre-[0-9\.]+\.tar\.gz$/,
		version => qr/^djvulibre-([0-9\.]+)\.tar\.gz$/,
	);
	plugin 'Extract' => 'tar.gz';
	plugin 'Build::Make' => 'gmake';
	plugin 'Build::Autoconf';
	build [
		'%{configure} --disable-xmltools --disable-desktopfiles --enable-shared --enable-static',
		'%{make}',
		'%{make} install',
	];
	after gather => sub {
		my ($build) = @_;

		my @extra_compiler_flags;

		if( $^O eq 'MSWin32' ) {
			# possibly only needed for MinGW
			push @extra_compiler_flags, qw(-DDDJVUAPI_EXPORT -DMINILISPAPI_EXPORT);
		}

		my @extra_linker_flags;

		push @extra_linker_flags, ExtUtils::CppGuess->new->linker_flags;

		if( $^O eq 'darwin' ) {
			push @extra_linker_flags, qw(-framework CoreFoundation);
		}

		for my $type ('', '_static') {
			$build->runtime_prop->{"cflags$type"} = join ' ',
				$build->runtime_prop->{"cflags$type"},
				@extra_compiler_flags;
			$build->runtime_prop->{"libs$type"}   = join ' ',
				$build->runtime_prop->{"libs$type"},
				@extra_linker_flags;
		}
	};
	plugin 'Gather::IsolateDynamic';
};
