include config/make/rules.mk
OS_NAME := kosmos

# version numbering deployed by ci deploy script - no necessary for local build
ifdef SW_KERNEL
VERSION := -$(SW_KERNEL).$(SW_MAJOR).$(SW_MINOR).$(CI_BUILD_ID)
else
VERSION :=
endif

MAIN_FILE = $(EXE_DIR)/lib$(OS_NAME)-$(ARCH)-$(BOARD)$(VERSION)$(DBG_EXT)$(LIB_EXT)
DEPLOY_PACKET = lib$(OS_NAME)-$(ARCH)-$(BOARD)$(VERSION)$(DBG_EXT).tar.xz

TEST_FILE = $(EXE_DIR)/$(TEST_APP)$(ELF_EXT)
BIN_FILE = $(EXE_DIR)/$(TEST_APP)$(BIN_EXT)
HEX_FILE = $(EXE_DIR)/$(TEST_APP)$(HEX_EXT)
SIZE_FILE = $(SIZE_DIR)/$(TEST_APP)$(SIZE_EXT)
MAP_FILE = $(MAP_DIR)/$(TEST_APP)$(MAP_EXT)

#include subfolders
include source/firmware/firmware.mk
ifdef TEST_APP
include source/test/test.mk
C_FLAGS += -DTEST_APP
endif

C_SOURCES := $(foreach folder, $(SRC_DIR), $(wildcard $(folder)/*.c))
C_OBJECTS := $(C_SOURCES:%.c=$(OBJ_DIR)/%.o)
C_DEPS := $(C_SOURCES:%.c=$(OBJ_DIR)/%.d)

all: $(MAIN_FILE)

deploy: all
	@$(MKDIR) $(EXE_DIR)/include
	$(ROOT_DIR)/source/scripts/board_interface.py -b "$(ROOT_DIR)/source/firmware/arch/$(CPU)/board/$(BOARD)/include/$(BOARD).h" -o "$(EXE_DIR)/include/board_devices.h"
	$(ROOT_DIR)/source/scripts/stack_interface.py -i "$(ROOT_DIR)/source/firmware/arch/$(CPU)/include/$(CPU)_stack.h" -o "$(EXE_DIR)/include/stack.h"
	cp $(ROOT_DIR)/source/firmware/kernel/interface/*.* $(EXE_DIR)/include/
	tar cvJf $(DEPLOY_PACKET) -C $(EXE_DIR) .


$(MAIN_FILE): $(C_OBJECTS)
	@$(MKDIR) $(EXE_DIR)
	$(AR) $(AR_FLAGS) $(MAIN_FILE) $(C_OBJECTS)

$(OBJ_DIR)/%.o: %.c
	@mkdir -p $(OBJ_DIR)
	@$(foreach folder, $(SRC_DIR), $(shell mkdir -p $(OBJ_DIR)/$(folder)))
	$(call makedep,$<,$@,$(subst .o,.d,$@),$(GEN_FLAGS) $(C_FLAGS))
	$(CC) $(GEN_FLAGS) $(C_FLAGS) -c -o "$@" "$<"

test: $(C_OBJECTS)
	@$(MKDIR) $(EXE_DIR)
	@$(MKDIR) $(MAP_DIR)
	@$(MKDIR) $(SIZE_DIR)
	$(CXX) $(GEN_FLAGS) $(L_FLAGS) -Wl,-Map,"$(MAP_FILE)" -o "$(TEST_FILE)" $(C_OBJECTS)
	$(OBJCOPY) $(TEST_FILE) -O binary $(BIN_FILE) 
	$(OBJCOPY) $(TEST_FILE) -O ihex $(HEX_FILE)
	$(NM) --size-sort --print-size $(TEST_FILE) > $(SIZE_FILE)
	@echo
	@$(SIZE) --format=berkeley -x $(TEST_FILE)
	@echo

clean:
	$(foreach folder, $(SRC_DIR), $(shell rm -f $(OBJ_DIR)/$(folder)/*.o))
	$(foreach folder, $(SRC_DIR), $(shell rm -f $(OBJ_DIR)/$(folder)/*.d))
	-rm -f $(OBJ_DIR)/*.o \
	$(OBJ_DIR)/*.d \
	$(MAIN_FILE) \
	$(BIN_FILE)

distclean:
	-rm -rf $(ROOT_DIR)/release

install: all
	$(PRE_PROGRAM)
	$(PROGRAM)

ifneq "$(MAKECMDGOALS)" "clean"
-include $(C_DEPS)
else
ifneq "$(MAKECMDGOALS)" "distclean"
-include $(C_DEPS)
endif
endif