# Copyright 1999-2017 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
# $Header: $

EAPI=6

inherit autotools eutils flag-o-matic toolchain-funcs

SRC_DATA="mirror://sourceforge/${PN}/Data"
SRC_D2X="http://www.descent2.de/files"
SRC_FILE="${PN}-src-${PV}.7z"
DATA_FILE="${PN}-data-1.18.64.7z"

DESCRIPTION="Descent 2 engine supporting high-resolution textures"
HOMEPAGE="http://www.descent2.de/"

# www.descent2.de must be *first* in the SRC_URI list, because
# all the SourceForge links exhaust Portage's retry patience.
SRC_URI="${SRC_D2X}/${SRC_FILE}
	${SRC_D2X}/${DATA_FILE}
	models? ( ${SRC_DATA}/hires-models.7z )
	sounds? ( ${SRC_DATA}/hires-sounds.7z )
	textures? (
		descent1? ( ${SRC_DATA}/D1-textures-512x512.7z )
		descent2? ( ${SRC_DATA}/D2-textures-512x512.7z )
	)"

LICENSE="D1X"
SLOT="0"
KEYWORDS="~amd64 ~x86"
IUSE="+data descent1 descent2 descent2-vertigo debug models openmp sounds textures"

CDEPEND="media-libs/glew:0=
	media-libs/libsdl:0=[joystick,opengl,sound,video]
	media-libs/sdl-mixer:0=
	media-libs/sdl-net:0=
	net-misc/curl:0=
	virtual/opengl"

RDEPEND="${CDEPEND}
	data? (
		descent1? ( games-action/descent1-data )
		descent2? ( || ( games-action/descent2-data games-action/descent2-demodata ) )
		descent2-vertigo? ( games-action/descent2-vertigo ) )"

DEPEND="${CDEPEND}
	app-arch/p7zip"

S="${WORKDIR}"
DIR="/usr/share/games/${PN}"
PATCHES=( "${FILESDIR}"/flags.patch )

src_unpack() {
	unpack "${SRC_FILE}" ./${PN}-makefiles.7z
}

src_prepare() {
	default

	# Use our own data directory.
	sed -i "/DEFAULT_GAME_FOLDER/s:/usr/local/games/${PN}:${EPREFIX}${DIR}:g" \
		main/gamefolders.cpp || die

	rm configure || die # Not executable!?
	eautoreconf
}

src_configure() {
	if use openmp && tc-has-openmp; then
		append-cppflags -fopenmp
		export LIBS+=" -lgomp"
	fi

	econf \
		--with-opengl \
		$(use_enable debug) \
		$(usex debug --disable-release --enable-release)
}

src_install() {
	dobin ${PN}
	newicon ${PN}-icon-64x64.png ${PN}.png
	make_desktop_entry ${PN} D2X-XL ${PN}

	# Unpack D2X-XL data files.
	dodir "${DIR}"
	cd "${ED}${DIR}" || die
	unpack "${DATA_FILE}"

	# Symlink original data files, which may or may not be present.

	if use descent1; then
		ln -s ../../d1x/descent.{hog,pig} data/ || die
	fi

	if use descent2; then
		ln -s ../../d2x/descent2.{ham,hog,s11,s22} data/ || die
		ln -s ../../d2x/{groupa,alien{1,2},fire,ice,water}.pig data/ || die
	fi

	if use descent2-vertigo; then
		ln -s ../../d2x/hoard.ham data/ || die
		mkdir missions || die
		ln -s ../../d2x/missions/d2x.{hog,mn2} missions/ || die
	fi

	# Optional data.
	use models && unpack hires-models.7z
	use sounds && unpack hires-sounds.7z

	if use textures; then
		use descent1 && unpack "D1-textures-512x512.7z"
		use descent2 && unpack "D2-textures-512x512.7z"
	fi
}