ROOT_DIR := $(shell pwd)

LVGL_DIR_NAME ?= lvgl

CC ?= gcc

TARGET_NAME := demo

BUILD_DIR := build
OBJ_DIR := $(BUILD_DIR)/obj
BIN_DIR := $(BUILD_DIR)/bin
TARGET := $(BIN_DIR)/$(TARGET_NAME)

IMG_SRC_DIR := user/images

# 图片文件名固定为 logo，后缀可以是 png / jpg / jpeg / bmp
LOGO_NAME := logo
LOGO_IMG_EXTS := png jpg jpeg bmp
LOGO_IMG_FILES := $(foreach ext,$(LOGO_IMG_EXTS),$(IMG_SRC_DIR)/$(LOGO_NAME).$(ext))
LOGO_IMG := $(firstword $(wildcard $(LOGO_IMG_FILES)))

LOGO_C := $(LOGO_NAME).c

LVGL_IMG_CONV := lv_img_conv
LVGL_IMG_CF := CF_TRUE_COLOR_ALPHA

APP_CSRCS := $(filter-out logo.c,$(wildcard *.c))
APP_CSRCS += $(shell if [ -d src ]; then find src -type f -name "*.c"; fi)

LVGL_CSRCS := $(shell if [ -d $(LVGL_DIR_NAME)/src ]; then find $(LVGL_DIR_NAME)/src -type f -name "*.c"; fi)

LV_DRIVERS_CSRCS := $(shell if [ -d lv_drivers ]; then find lv_drivers -type f -name "*.c"; fi)

CSRCS := $(APP_CSRCS)
CSRCS += $(LVGL_CSRCS)
CSRCS += $(LV_DRIVERS_CSRCS)
CSRCS += $(LOGO_C)

OBJS := $(patsubst %.c,$(OBJ_DIR)/%.o,$(CSRCS))

CFLAGS ?= -O3 -g0
CFLAGS += -Wall
CFLAGS += -I.
CFLAGS += -I$(LVGL_DIR_NAME)
CFLAGS += -I$(LVGL_DIR_NAME)/src
CFLAGS += -Ilv_drivers
CFLAGS += -Iinclude

LDFLAGS += -lm

.PHONY: all
all: $(TARGET)

$(BIN_DIR):
	mkdir -p $(BIN_DIR)

$(OBJ_DIR):
	mkdir -p $(OBJ_DIR)

$(LOGO_C): $(LOGO_IMG)
	@if [ -z "$(LOGO_IMG)" ]; then \
		echo "Error: 未找到图片文件"; \
		echo "请将图片命名为以下任意一种格式，并放入 $(IMG_SRC_DIR) 目录："; \
		echo "  logo.png"; \
		echo "  logo.jpg"; \
		echo "  logo.jpeg"; \
		echo "  logo.bmp"; \
		exit 1; \
	fi
	@echo "Use image: $(LOGO_IMG)"
	rm -f $(LOGO_C)
	cp $(LOGO_IMG) ./$(notdir $(LOGO_IMG))
	$(LVGL_IMG_CONV) $(notdir $(LOGO_IMG)) -f -c $(LVGL_IMG_CF)
	rm -f ./$(notdir $(LOGO_IMG))

$(OBJ_DIR)/%.o: %.c
	mkdir -p $(dir $@)
	$(CC) $(CFLAGS) -c $< -o $@

$(TARGET): $(LOGO_C) $(OBJS) | $(BIN_DIR)
	$(CC) $(OBJS) -o $(TARGET) $(LDFLAGS)
	@echo "Build success: $(TARGET)"

.PHONY: clean
clean:
	rm -rf $(OBJ_DIR)
	rm -f $(TARGET)

.PHONY: imgclean
imgclean:
	rm -f $(LOGO_C)

.PHONY: distclean
distclean:
	rm -rf $(BUILD_DIR)
	rm -f $(LOGO_C)

.PHONY: info
info:
	@echo "TARGET = $(TARGET)"
	@echo "IMG_SRC_DIR = $(IMG_SRC_DIR)"
	@echo "LOGO_IMG = $(LOGO_IMG)"
	@echo "LOGO_C = $(LOGO_C)"
	@echo "Support image formats: $(LOGO_IMG_EXTS)"
	@echo "CSRCS = $(CSRCS)"
