# Example Makefile to compile a RapidWright shared library for use in C++.
# Author: Chris Lavin (Xilinx Inc.)
# 5/31/2019

# to run from scratch just run 'make' in this directory 
# This Makefile should come with the files:
# (1) RapidWrightAPI.java
# (2) RapidWrightExample.cpp

GRAAL_PATH := $(shell pwd)/graalvm-ce-19.0.0/bin
RAPIDWRIGHT_PATH := $(shell pwd)/RapidWright
JAR_PATH=$(RAPIDWRIGHT_PATH)/jars

.PHONY: all install_graal install_rapidwright remove_jython add_example compile_sharedlib compile_example run_example

####################################################################################################

# This target will run all steps in order (installing RapidWright and Graal, updating RapidWright, compiling the .so and the compiling and running the example)
all: install_graal install_rapidwright remove_jython add_example compile_sharedlib compile_example run_example

# Installs the GraalVM tool and native-image package
install_graal:
	wget https://github.com/oracle/graal/releases/download/vm-19.0.0/graalvm-ce-linux-amd64-19.0.0.tar.gz
	tar zxf graalvm-ce-linux-amd64-19.0.0.tar.gz
	$(GRAAL_PATH)/gu install native-image

# Installs RapidWright with source code
install_rapidwright:
	wget http://www.rapidwright.io/docs/_downloads/rapidwright-installer.jar
	export PATH=$(GRAAL_PATH):$(PATH) && java -jar rapidwright-installer.jar -t -k

# Removes the one file dependency in RapidWright on Jython and removes unnecessary jars
remove_jython:
	rm $(RAPIDWRIGHT_PATH)/bin/com/xilinx/rapidwright/util/RapidWright.class
	rm $(RAPIDWRIGHT_PATH)/src/com/xilinx/rapidwright/util/RapidWright.java
	rm $(JAR_PATH)/{jython-standalone-2.7.0,jupyter-kernel-jsr223,jeromq-0.3.6,json,junit-4.12}.jar

# Adds an example file and compiles it for use with the C++ calls to the RapidWright project/classpath
add_example:
	cp RapidWrightAPI.java $(RAPIDWRIGHT_PATH)/src/com/xilinx/rapidwright/examples
	$(GRAAL_PATH)/javac -cp $(RAPIDWRIGHT_PATH)/bin:$(shell find $(JAR_PATH) -name '*.jar' | grep -Ev 'jython|jupyter|win64|jeromq|json|junit' | tr '\n' ':') $(RAPIDWRIGHT_PATH)/src/com/xilinx/rapidwright/examples/RapidWrightAPI.java -d $(RAPIDWRIGHT_PATH)/bin

# Compiles the shared library (.so) for RapidWright
compile_sharedlib:
	$(GRAAL_PATH)/native-image --no-server -cp $(RAPIDWRIGHT_PATH)/bin:$(shell find $(JAR_PATH) -name '*.jar' | grep -Ev 'jython|jupyter|win64|jeromq|json|junit' | tr '\n' ':') --no-fallback --initialize-at-build-time --shared -H:Name=librapidwright

# Compiles a small C++ example program to test our RapidWright shared library
compile_example:
	g++ RapidWrightExample.cpp -I. -L. -lrapidwright

# Runs the example C++ program, should print out a few tile names from the device provided
run_example:
	export LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH && export RAPIDWRIGHT_PATH=$(RAPIDWRIGHT_PATH) && ./a.out xcvu9p

