.PHONY: all clean

# C&GO编译器
CC = gcc
AR = ar
DEFINS = -D_GNU_SOURCE

GO := go
GO_BUILD := $(GO) build
GO_FLAGS := -ldflags "-s -w -X hnyfkj.com.cn/rtu/linux/baseapp.Version=1.0.0.1 -X hnyfkj.com.cn/rtu/linux/baseapp.BuildTime=$(shell date +%Y-%m-%dT%H:%M:%S)"

target ?= x86_64
ifeq ($(target),armv7hf)
  GOOS := linux
  GOARCH := arm
  GOARM := 7
  CC := arm-linux-gnueabihf-gcc
  AR := arm-linux-gnueabihf-ar
endif

# GO编译环境
SETGO_ENV = \
	$(if $(GOOS),GOOS=$(GOOS)) \
	$(if $(GOARCH),GOARCH=$(GOARCH)) \
	$(if $(GOARM),GOARM=$(GOARM)) \
	CC=$(CC) CGO_ENABLED=1 \

# 日期和时间
DATE := $(shell date +%Y%m%d_%H%M%S)

# 编译的目标
all : mvs_u_takephoto.out air720u_4g.out rtu_linux_modules.out

# 通用基础库
libswapi.a :
	$(MAKE) -C swapi target=$(target) $@

# 海康机器人
libmvs_u_takephoto.a :
	$(MAKE) -C mvs_u_takephoto target=$(target) $@

# "Air720U"
libair720u.a :
	$(MAKE) -C air720u target=$(target) $@

# "Air530Z"
libair530z.a :
	$(MAKE) -C air530z target=$(target) $@

# 海康相机拍照测试
LIB1 := -Wl,-Bstatic -L./swapi -lswapi -L./mvs_u_takephoto -lmvs_u_takephoto
ifeq ($(target),armv7hf)
  LIB1 += -Wl,-Bdynamic -lc -lm -ldl -lpthread -L$(PWD)/mvs_u_takephoto/lib/armv7hf/. -lMvCameraControl
else
  LIB1 += -Wl,-Bdynamic -lc -lm -ldl -lpthread -L$(PWD)/mvs_u_takephoto/lib/x86_64/64 -lMvCameraControl
endif
mvs_u_takephoto.out : libswapi.a libmvs_u_takephoto.a ./tests/mvs_u_takephoto/main.go
	mkdir -p ./build/takephoto_test
	$(GO) mod tidy
	$(SETGO_ENV) CGO_LDFLAGS="$(LIB1)" $(GO_BUILD) $(GO_FLAGS) -o $@ ./tests/mvs_u_takephoto/main.go
	@cp $@ ./build/takephoto_test/$(basename $@)_$(DATE)$(suffix $@)
	rm -rf $@

# 测4G模块Air720U
LIB2 := -Wl,-Bstatic -L./swapi -lswapi -L./air720u -lair720u -Wl,-Bdynamic -lc -lm -ldl -lpthread
air720u_4g.out : libswapi.a libair720u.a ./tests/air720u/main.go
	mkdir -p ./build/air720u_test
	$(GO) mod tidy
	$(SETGO_ENV) CGO_LDFLAGS="$(LIB2)" $(GO_BUILD) $(GO_FLAGS) -o $@ ./tests/air720u/main.go
	@cp $@ ./build/air720u_test/$(basename $@)_$(DATE)$(suffix $@)
	rm -rf $@

# 主测试程序
LIB3 := -Wl,-Bstatic -L./swapi -lswapi -L./mvs_u_takephoto -lmvs_u_takephoto -L./air720u -lair720u -L./air530z -lair530z
ifeq ($(target),armv7hf)
  LIB3 += -Wl,-Bdynamic -lc -lm -ldl -lpthread -L$(PWD)/mvs_u_takephoto/lib/armv7hf/. -lMvCameraControl
else
  LIB3 += -Wl,-Bdynamic -lc -lm -ldl -lpthread -L$(PWD)/mvs_u_takephoto/lib/x86_64/64 -lMvCameraControl
endif
rtu_linux_modules.out : libswapi.a libmvs_u_takephoto.a libair720u.a libair530z.a ./main.go
	mkdir -p ./build
	$(GO) mod tidy
	$(SETGO_ENV) CGO_LDFLAGS="$(LIB3)" $(GO_BUILD) $(GO_FLAGS) -o $@ ./main.go
	@cp $@ ./build/$(basename $@)_$(DATE)$(suffix $@)

# 编译的清理
clean :
	make -C ./swapi clean
	make -C ./mvs_u_takephoto clean
	make -C ./air720u clean
	make -C ./air530z clean
	rm -rf ./*.a ./*.out ./build
