use alienfile;

plugin 'PkgConfig' => (
	pkg_name => 'poppler',
	minimum_version => '0.52.0',
);

requires 'Alien::gmake';
requires 'Alien::Build::Plugin::Gather::Dino';
requires 'Alien::OpenJPEG';
requires 'Env::ShellWords' => '0.01';
requires 'Path::Tiny' => 0;
use Env qw($LDFLAGS);

# https://poppler.freedesktop.org/
share {
	plugin Download => (
		url => 'https://poppler.freedesktop.org/releases.html',
		version => qr/poppler-([\d.]+)\.tar\.xz/,
	);

	plugin Extract => 'tar.xz';

	# warn is fine here because this is part of configure-time
	eval {
		require Alien::OpenJPEG;
		$LDFLAGS .= ' ' . Alien::OpenJPEG->libs;
	} or warn "Unable to add to \$LDFLAGS ($LDFLAGS): $@";
	plugin 'Build::SearchDep' => (
		aliens => [ qw( Alien::OpenJPEG ) ],
	);


	patch sub {
		my($splash_bitmap) = Path::Tiny->new('splash/SplashBitmap.h');
		$splash_bitmap->edit_lines(sub {
			s{\Qpoppler/GfxState.h\E}{GfxState.h}g;
		});

		# Bug in Poppler v0.61: uses `@CMAKE_INSTALL_LIBDIR@` instead
		# of either `@CMAKE_INSTALL_FULL_LIBDIR@` or
		# `${prefix}/@CMAKE_INSTALL_LIBDIR@`.
		my @pc_cmake_paths = Path::Tiny->new('.')->children(qr/\Q.pc.cmake\E$/);
		for my $pc_cmake_file (@pc_cmake_paths) {
			$pc_cmake_file->edit_lines(sub {
				s[libdir=\@CMAKE_INSTALL_LIBDIR@][libdir=\${prefix}/\@CMAKE_INSTALL_LIBDIR@]g;
				s[includedir=\@CMAKE_INSTALL_INCLUDEDIR@][includedir=\${prefix}/\@CMAKE_INSTALL_INCLUDEDIR@]g;
			});
		}

	};

	build [
		[ 'cmake', qw(-G), 'Unix Makefiles',
			'-DCMAKE_INSTALL_PREFIX:PATH=%{.install.prefix}',
			'-DENABLE_XPDF_HEADERS=ON',
			( '-DENABLE_GLIB=OFF' )x!!( $^O eq 'darwin' ),
			'.' ],
		[ '%{gmake}' ],
		[ '%{gmake}', 'install' ],
	];

	plugin 'Gather::Dino';
};
