#  Copyright (c) 1997-2009
#  Ewgenij Gawrilow, Michael Joswig (Technische Universitaet Darmstadt, Germany)
#  http://www.polymake.de
#
#  This program is free software; you can redistribute it and/or modify it
#  under the terms of the GNU General Public License as published by the
#  Free Software Foundation; either version 2, or (at your option) any
#  later version: http://www.gnu.org/licenses/gpl.txt.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#-------------------------------------------------------------------------------
#  $Project: polymake $$Id: extension.make 9405 2009-12-20 18:14:59Z gawrilow $


###########################################################
#
#  Building and installing a polymake extension
#

ExtensionName := $(notdir ${CURDIR})

.PHONY: all install install-bin install-shared clean TAGS RTAGS test

include ${ProjectTop}/support/utils.make
include ${BuildDir}/conf.make

InstallTop  := ${InstallTop}/extensions/${ExtensionName}
InstallArch := ${InstallArch}/extensions/${ExtensionName}

Apps := $(notdir $(wildcard apps/*))

define _MakeAppBin
	$(MAKE) -C $(notdir ${BuildDir})/apps/$(1) AppName=$(1) $(2)

endef
define _MakeAppsBin
	$(foreach a,${Apps},$(call _MakeAppBin,$a,$(1)))
endef
define _InstallSubdir
${PERL} ${INSTALL_PL} -m ${DirMask} -U $(2) $(1) ${InstallTop}/$(1)

endef
define _InstallShared
	$(foreach d, perllib rules scripts, $(if $(wildcard $(1)/$d), $(call _InstallSubdir,$(1)/$d)))
endef
define _CreateDir
${PERL} ${INSTALL_PL} -d -m ${DirMask} $(1)

endef

all:
	@+$(call _MakeAppsBin,all-lib)

install: install-shared install-bin

install-bin: all
	$(call _CreateDir,${InstallArch}/lib)
	@+$(call _MakeAppsBin, install InstallTop=${InstallTop} InstallArch=${InstallArch})
	if [ -f $(notdir ${BuildDir})/conf.make ]; then \
	   ${PERL} ${INSTALL_PL} -m 444 $(notdir ${BuildDir})/conf.make ${InstallArch}; \
	fi

install-shared:
	$(call _CreateDir,${InstallTop})
	$(foreach a, ${Apps}, $(call _InstallShared,apps/$a))
	@+$(call _MakeAppsBin, install-src InstallTop=${InstallTop})
	$(if $(wildcard scripts), $(call _InstallSubdir,scripts))
	if [ -f URI ]; then \
	  ${PERL} ${INSTALL_PL} -m 444 URI ${InstallTop}; \
	fi

clean:
	@+$(call _MakeAppsBin, clean)

tagsFLAGS = -R -e -f $@ --exclude=.svn --exclude='.\#*' --exclude='\#*' --exclude='*~'

TAGS:
	ctags ${tagsFLAGS} --language-force=c++ apps/*/{src,include}
RTAGS:
	ctags ${tagsFLAGS} --language-force=perl $(wildcard apps/*/{perllib,rules,scripts} scripts)

AppsWithTests := $(foreach a,${Apps},$(if $(wildcard apps/$a/testsuite), $a))

ifdef AppsWithTests
test : all
	polymake --script run_testcases --applications ${AppsWithTests} --extensions ${CURDIR}
else
test :
	@echo No testcases found!
	@false
endif
