#
# Makefile to build the Polo library
#

# Main target
#   polo:        creates a jar containing the protocol (default)
#   poloJava:    compiles the java sources
#   proto:       compiles the protocol buffers

.PHONY: proto polo poloJava clean cleanProto default

default: polo

###############
# DEFINITIONS #
###############
# Sources top directory
JAVA_SRC_TOP := src

# Package name
PACKAGE_NAME := com/google/polo

# Complete path to sources
JAVA_SRC_DIR := $(JAVA_SRC_TOP)/$(PACKAGE_NAME)

JAVA_SRC := $(shell find $(JAVA_SRC_DIR) -name '*.java')

# .class targets
JAVA_SRC_CLASSES = $(patsubst %.java,%.class,$(JAVA_SRC))

# Classpath 
JAVA_CLASSPATH := $(subst jar ,jar:,$(strip "bin:$(wildcard jar/*.jar)"))

# Location to put the generated .class
JAVA_OUT := bin

# Name for the jar that will be created
JAR_NAME := polo.jar

####################
# PROTOCOL BUFFERS #
####################
# Sources directory for protocols buffers
PROTO_SRC_DIR := ../proto

# Location for the java files generated by the proto compiler
PROTO_JAVA_OUT := proto_out

# Creates the needed directories
$(PROTO_JAVA_OUT) $(JAVA_OUT):
	-mkdir -p $@

# Definition of the .proto and the corresponding java generated files.
$(PROTO_JAVA_OUT)/$(PACKAGE_NAME)/wire/protobuf/PoloProto.java: $(PROTO_SRC_DIR)/polo.proto
	$(genproto)

# All java files generated from proto.
ALL_GENPROTOS := \
	$(PROTO_JAVA_OUT)/$(PACKAGE_NAME)/wire/protobuf/PoloProto.java

# Rule to build a .proto in the proto/ directory
define genproto
	protoc \
	  --java_out=$(PROTO_JAVA_OUT) \
	  -I $(PROTO_SRC_DIR) \
	  $<
endef

# Compiles the proto
proto: $(PROTO_JAVA_OUT) $(ALL_GENPROTOS)

#################
# JAVA COMPILER #
#################
# compiles a java source
%.class: %.java
	javac \
	  -sourcepath "$(JAVA_SRC_TOP):$(PROTO_JAVA_OUT)" \
	  -classpath $(JAVA_CLASSPATH) \
	  -d $(JAVA_OUT)/ \
	  $?

#################
# PROJECT RULES #
#################
# Compiles the java sources for the project
poloJava: $(JAVA_OUT) proto $(JAVA_SRC_CLASSES)

# Cleans the generated protocol buffers
cleanProto:
	-rm -rf $(PROTO_JAVA_OUT)

# Cleans the project
clean: cleanProto
	-rm -rf $(JAVA_OUT)
	-rm $(JAR_NAME)

# Complete and clean build of the project returns a jar.
polo: clean poloJava
	jar cf $(JAR_NAME) -C $(JAVA_OUT) $(shell ls $(JAVA_OUT))