use alienfile;

# Do not probe for system libmupdf becasue we need to compile with shared
# library flags.

share {
	requires 'Alien::gmake' => 0.14;
	requires 'Alien::patch' => 0.08;
	requires 'Path::Tiny' => 0;
	requires 'Net::SSLeay' => 0;
	requires 'IO::Socket::SSL' => 0;

	plugin Download => (
		url => 'https://mupdf.com/downloads/',
		version => qr/mupdf-([\w\.]+)-source\.tar\.gz/,
	);

	if( exists $ENV{MSYSTEM} ) {
		# See <https://github.com/Perl5-Alien/Alien-Build/issues/13>.

		# Using CommandLine to extract rather than ArchiveTar because
		# the extraction using ArchiveTar is not always successful on
		# Windows.  This can happen because the mupdf tarball contains
		# long paths that can push the entire path over the 260
		# character path limit.
		#plugin 'Extract::CommandLine' => 'tar.gz';

		# Use regular Extract plugin due to symlink in tarball.
		plugin Extract => 'tar.gz';
	} else {
		plugin Extract => 'tar.gz';
	}

	plugin 'Build::MSYS' => ();
	my @XCFLAGS;
	if( $^O eq 'MSWin32' ) {
		# builds on Windows are already position independent
	} else {
		push @XCFLAGS, '-fPIC';
	};

	# Do not embed some fonts
	push @XCFLAGS, qw(-DTOFU -DTOFU_CJK);

	my @EXTRA_MAKE_FLAGS = ();

	build [
		( '%{patch} -p1 < %{.install.patch}/0001-Use-argfile-for-ar.patch' ) x!!( $^O eq 'MSWin32' ),
		'%{patch} -p1 < %{.install.patch}/0002-jbig2dec-win32-stdlib.patch',
		[
			'%{gmake}',
			'verbose=yes',
			'prefix=%{.install.prefix}',
			'install',

			# OpenGL
			'HAVE_GLFW=no',
			'HAVE_GLUT=no',

			# X11
			'HAVE_X11=no',

			# Extra CFLAGS
			"XCFLAGS=@XCFLAGS",

			@EXTRA_MAKE_FLAGS,

			# Do not build apps other than `mutool`.
			q|VIEW_APPS=|,
			q|TOOL_APPS=$(MUTOOL_EXE)|,
		]
	];

	gather sub {
		my($build) =@_;
		my $prefix = $build->runtime_prop->{prefix};
		$build->runtime_prop->{cflags}        = "-I$prefix/include";
		$build->runtime_prop->{cflags_static} = "-I$prefix/include";
		$build->runtime_prop->{libs}          = "-L$prefix/lib";
		$build->runtime_prop->{libs_static}   = "-L$prefix/lib";
	};
};
