
.PHONY: FORCE default
CV_DIR := $(shell pwd)/../opencv
CV_INSTALL_DIR := $(CV_DIR)/install
CV_WASM_DIR := $(CV_DIR)/build/wasm
CXX := ccache g++
CXXFLAGS := -O2 -std=c++17 -Wall -Werror -g -I$(CV_INSTALL_DIR)/include/opencv4


ifeq ($(shell uname), Darwin)
	RPATH_FLAG := -Wl,-rpath,'@executable_path/lib'
	STATIC :=
	IMAGE_VIEWER := open
else
	RPATH_FLAG := -Wl,-rpath,'$$ORIGIN/lib'
	STATIC := 1
	IMAGE_VIEWER := feh
endif

USE_PULSAR :=

START_GROUP := -Wl,--start-group
END_GROUP := -Wl,--end-group

CV_PKG_CONFIG_PATH := $(shell pwd)/../opencv/install/lib/pkgconfig/

OPENCV_FLAGS := $(filter-out -lIconv::Iconv, \
	$(shell PKG_CONFIG_PATH=$(CV_PKG_CONFIG_PATH) pkg-config opencv4 --libs --cflags $(if $(STATIC), --static)) \
)

default: qrtool qrtool.wx.wasm.br qrtool.web.js

qrtool: CXXFLAGS += -DWECHAT_QRCODE_USE_MODEL=1

qrtool: qrtool.cpp libqr.cpp \
	$(if $(USE_PULSAR), mq_worker.cpp) \
	base64.cpp mq_worker.h base64.h \
	http.o \
	Makefile
	$(CXX) -o $@ \
		$(if $(STATIC), -static) \
		$(filter %.cpp %.o, $^) \
		-DQRTOOL_MAIN=1 \
		$(if $(USE_PULSAR), -lpulsar) \
		$(CXXFLAGS) \
		$(RPATH_FLAG) \
		$(if $(STATIC), $(START_GROUP) -ljbig) \
		$(OPENCV_FLAGS) \
		$(if $(STATIC), $(END_GROUP)) \
		-Wno-error=unused-function \

qrtool.zip: qrtool
	rm -rf qrtool.zip-workdir
	mkdir -p qrtool.zip-workdir
	cp qrtool qrtool.zip-workdir/qrtool.$(shell git describe --always).x86_64
	cd qrtool.zip-workdir && zip qrtool.zip qrtool.$(shell git describe --always).x86_64 && mv qrtool.zip ..
	rm -rf qrtool.zip-workdir

qrtool.web.js: EMCC_FLAGS := \
		-O3

qrtool.wx.js: EMCC_FLAGS := \
		-O3 \
		--pre-js pre.wx.js \
		--post-js post.wx.js

SIMD128_OPTS := -msimd128
SIMD128_OPTS :=

qrtool.wx.js: pre.wx.js post.wx.js
qrtool.wx.js qrtool.web.js: qrtool_wasm.cpp libqr.cpp Makefile
	source ../../emsdk/emsdk_env.sh && emcc \
		-o $@ -I$(CV_INSTALL_DIR)/include/opencv4 $(filter %.cpp, $^) \
		$(addprefix $(CV_WASM_DIR)/lib/, \
		libopencv_core.a \
		libopencv_dnn.a \
		libopencv_imgproc.a \
		libopencv_wechat_qrcode.a \
		) \
		$(addprefix $(CV_WASM_DIR)/3rdparty/lib/, \
		libzlib.a) \
		'-sEXPORTED_FUNCTIONS=["_qrtool_angle","_malloc","_free"]' \
		'-sEXPORTED_RUNTIME_METHODS=["ccall","cwrap","_wasm_call_ctors"]' \
		"-sMIN_CHROME_VERSION=73" \
		"-sMIN_SAFARI_VERSION=140100" \
		-sALLOW_MEMORY_GROWTH=1 \
		-sENVIRONMENT=web \
		$(SIMD128_OPTS) \
		-std=c++17 \
		-fexceptions \
		-lembind \
		-g1 \
		-sWASM=1 \
		$(EMCC_FLAGS)

qrtool.wx.wasm.br: qrtool.wx.js
	brotli -kf qrtool.wx.wasm

install-scanner: qrtool.wx.wasm.br
	@cp -v qrtool.wx.js qrtool.wx.wasm.br ../scanner/pages/emblemscanner/
	@cp -v qrtool.wx.js ../scanner/pages/emblemscanner/worker/

install-web: qrtool.web.wasm
	@cp -v qrtool.web.js qrtool.web.wasm ../web/public/camera-5.0/js/

install: install-web install-scanner
