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

EAPI=2

inherit games eutils

MY_P="${PN/-/_}-${PV}-src"
DESCRIPTION="The quest for the mystifyingly fabulous Orb of Zot"
HOMEPAGE="http://crawl-ref.sourceforge.net/"
SRC_URI="mirror://sourceforge/crawl-ref/${MY_P}.tbz2"

LICENSE="crawl"
SLOT="0"
KEYWORDS="~x86 ~amd64"
IUSE="sdl unicode"

CDEPEND="dev-db/sqlite:3
	dev-lang/lua
	!sdl? ( sys-libs/ncurses[unicode?] )
	sdl? ( media-libs/libsdl[X,opengl] 
		media-libs/freetype:2 )"
DEPEND="${CDEPEND}
	media-libs/libpng"
RDEPEND="${CDEPEND}
	media-fonts/ttf-bitstream-vera"

S="${WORKDIR}/${MY_P}/source"

src_prepare() {
	# Pick the right makefile
	cp makefile$(use sdl && echo "_tiles").unix makefile

	# Lots of fixes and Gentoo-specific configs
	sed -i \
		-e "s/GAME = crawl/GAME = ${PN}/" \
		-e "/^INSTALLDIR/c INSTALLDIR := ${GAMES_BINDIR}" \
		-e "/^# DATADIR :=/a DATADIR := ${GAMES_DATADIR}/${PN}/" \
		-e "/^# SAVEDIR :=/a SAVEDIR := ${GAMES_STATEDIR}/${PN}/" \
		-e 's/${INSTALLDIR}/$(INSTALLDIR)/' \
		-e 's/$(INSTALLDIR)/$(DESTDIR)$(INSTALLDIR)/g' \
		-e 's/$(DATADIR)/$(DESTDIR)$(DATADIR)/g' \
		-e 's/$(SAVEDIR)/$(DESTDIR)$(SAVEDIR)/g' \
		-e '/^LDFLAGS = /d' \
		-e 's/ $(CFWARN) / /' \
		-e 's/ $(CFOTHERS)/ $(CFOTHERS) $(CFLAGS)/' \
		-e 's/ $(YCFLAGS) / $(CFLAGS) $(LDFLAGS) /' \
		-e 's/ $(LUASRC)$(LUALIBA) / /' \
		-e '/EXTRA_DEPENDS  += $(FSQLLIBA)/d' \
		makefile || die "sed failed"
	sed -i \
		-e 's/$(SDL_CFLAGS)/$(SDL_CFLAGS) $(CFLAGS)/' \
		-e 's/$(SDL_LDFLAGS)/$(SDL_LDFLAGS) $(LDFLAGS)/' \
		-e 's/ -lSDL_image -lpng/\
LD_ADD = -lSDL_image -lpng/' \
		-e 's/${LDFLAGS}/$(LD_ADD) $(LDFLAGS)/' \
		rltiles/makefile.unix || die "sed failed"

	# Fix icon location
	sed -i -e 's/#ifdef DATA_DIR_PATH/#ifdef FALSE/' tilesdl.cc || die "sed failed"

	# Make sure we don't pick-up any stray files from the internal lua and sqlite
	sed -i \
		-e 's:util/lua/src/.*\.h::' \
		-e 's:util/sqlite/.*\.h::' \
		makefile.dep || die "sed failed"
	rm -rf util/{lua,sqlite}

	if use unicode; then sed -i \
		-e 's/UNICODE_GLYPHS = n/UNICODE_GLYPHS = y/' \
		-e 's/UNICODE_LOCALE =/UNICODE_LOCALE = \./' \
		makefile || die "sed failed"
	fi

	# Use system fonts
	sed -i -e 's|datafile_path(font_name, false, true)|std::string("/usr/share/fonts/ttf-bitstream-vera/") + std::string(font_name)|' \
		tilefont.cc || die "sed failed"

	# Remove useless files that would get installed
	rm -f ../docs/{libpng-LICENSE,lualicense,pcre_license}.txt
	rm -f dat/tiles/stone_soup_icon-win32.png
	rm -f dat/tiles/*.ttf
}

src_install() {
	emake DESTDIR="${D}" install || die "Install failed"
	keepdir "${GAMES_STATEDIR}/${PN}"
	use sdl && make_desktop_entry "${PN}" "Dungeon Crawl Stone Soup" \
		"${GAMES_DATADIR}/${PN}/dat/tiles/stone_soup_icon-32x32.png" Game
	prepgamesdirs
	fperms 2770 "${GAMES_BINDIR}/${PN}" || die "fperms failed"
	fperms 770 "${GAMES_STATEDIR}/${PN}" || die "fperms failed"
}