.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)

# 依赖库路径
RTU_LINUX_MODULES_PATH := $(shell pwd)/../rtu_linux_modules

# 编译的目标
all : rtu_xy_v.out

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

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

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

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

#  "EC200U"
libec200u.a :
	$(MAKE) -C $(RTU_LINUX_MODULES_PATH)/ec200u target=$(target)  $@

# 单片机MCU
libmcu_ctrl_board.a :
	$(MAKE) -C mcu_ctrl_board target=$(target) $@

LIBS := -Wl,-Bstatic -L$(RTU_LINUX_MODULES_PATH)/swapi -lswapi -L$(RTU_LINUX_MODULES_PATH)/mvs_u_takephoto -lmvs_u_takephoto
LIBS += -L$(RTU_LINUX_MODULES_PATH)/air720u -lair720u -L$(RTU_LINUX_MODULES_PATH)/air530z -lair530z -L$(RTU_LINUX_MODULES_PATH)/ec200u -lec200u
LIBS += -L./mcu_ctrl_board -lmcu_ctrl_board
ifeq ($(target),armv7hf)
  LIBS += -Wl,-Bdynamic -lc -lm -ldl -lpthread -L$(RTU_LINUX_MODULES_PATH)/mvs_u_takephoto/lib/armv7hf/. -lMvCameraControl
else
  LIBS += -Wl,-Bdynamic -lc -lm -ldl -lpthread -L$(RTU_LINUX_MODULES_PATH)/mvs_u_takephoto/lib/x86_64/64 -lMvCameraControl
endif

# 可执行程序
rtu_xy_v.out : libswapi.a libmvs_u_takephoto.a libair720u.a libair530z.a libec200u.a libmcu_ctrl_board.a ./main.go
	mkdir -p ./build
	$(GO) mod tidy
	$(SETGO_ENV) CGO_LDFLAGS="$(LIBS)" $(GO_BUILD) $(GO_FLAGS) -o $@ ./main.go
	@cp $@ ./build/$(basename $@)_$(DATE)$(suffix $@)

# 编译的清理
clean :
	make -C $(RTU_LINUX_MODULES_PATH)/swapi clean
	make -C $(RTU_LINUX_MODULES_PATH)/mvs_u_takephoto clean
	make -C $(RTU_LINUX_MODULES_PATH)/air720u clean
	make -C $(RTU_LINUX_MODULES_PATH)/air530z clean
	make -C $(RTU_LINUX_MODULES_PATH)/ec200u  clean
	make -C ./mcu_ctrl_board clean
	rm -rf ./*.a ./*.out ./build
