#############################################################################
# Primesense template makefile.
# This file should not be made, but only included from other makefiles.
# By default, this makefile compiles in release. To compile a debug version:
#    make CFG=Debug
#
# Project makefile should define the following BEFORE including this file:
# SRC_FILES - a list of all source files
# JAR_NAME - name of the package
# BIN_DIR - Bin directory (output dir)
# INC_DIRS - a list of additional include directories
# LIB_DIRS - a list of additional library directories
# USED_JARS - a list of libraries used
# MAIN_CLASS - [Optional] for executable jar
#############################################################################

# take this file's dir
COMMON_CS_MAKE_FILE_DIR = $(dir $(lastword $(MAKEFILE_LIST)))

include $(COMMON_CS_MAKE_FILE_DIR)CommonDefs.mak

nullstring :=
space := $(nullstring) # end of the line

USED_JARS_OPTION =
ifneq "$(USED_JARS)" ""
	USED_JARS_PATH = $(foreach jar, $(USED_JARS), $(OUT_DIR)/$(jar).jar /usr/share/java/$(jar).jar)
	USED_JARS_OPTION = -cp $(subst $(space),:,$(strip $(USED_JARS_PATH)))
endif

OUTPUT_NAME = $(JAR_NAME).jar

# create manifest file if needed
JAR_MANIFEST_CREATE_COMMAND := 
MANIFEST_FILE := 
JAR_OPTIONS = -cf

ifneq (, $(if $(or $(MAIN_CLASS), $(USED_JARS)),1))
	JAR_OPTIONS = -cfm
	MANIFEST_FILE = Manifest.txt
	JAR_MANIFEST_CREATE_COMMAND = (
	ifneq (,$(MAIN_CLASS))
		JAR_MANIFEST_CREATE_COMMAND += echo "Main-Class: $(MAIN_CLASS)";
	endif
	ifneq (,$(USED_JARS))
		JAR_MANIFEST_CREATE_COMMAND += echo "Class-Path: $(USED_JARS_PATH)";
	endif
	JAR_MANIFEST_CREATE_COMMAND += ) > $(MANIFEST_FILE)
endif

CREATE_SHORTCUT = 
ifneq (, $(MAIN_CLASS))
	SHORTCUT = $(OUT_DIR)/$(JAR_NAME)
	CREATE_SHORTCUT = echo java -jar $(OUTPUT_NAME) > $(SHORTCUT); chmod +x $(SHORTCUT)
endif

#############################################################################
# Targets
#############################################################################
include $(COMMON_CS_MAKE_FILE_DIR)CommonTargets.mak

.PHONY: clean-manifest clean-int

# Final output file
$(OUTPUT_FILE): | $(INT_DIR)
	javac $(USED_JARS_OPTION) -d $(INT_DIR) $(SRC_FILES)
	$(JAR_MANIFEST_CREATE_COMMAND)
	jar $(JAR_OPTIONS) $@ $(MANIFEST_FILE) -C $(INT_DIR) .
	$(CREATE_SHORTCUT)

clean-manifest:
	rm -rf $(MANIFEST_FILE)
	
clean-int:
	rm -rf $(INT_DIR)
	
clean: clean-manifest clean-int


