-include local.mk
include macros.mk

PLATFORM ?= armemu
include platform.mk

TARGET := lk.bin
TARGETELF := lk
BUILDDIR := build-$(PLATFORM)

TOOLCHAIN_PREFIX := arm-elf-
CC := $(TOOLCHAIN_PREFIX)gcc
LD := $(TOOLCHAIN_PREFIX)ld
OBJDUMP := $(TOOLCHAIN_PREFIX)objdump
OBJCOPY := $(TOOLCHAIN_PREFIX)objcopy
CPPFILT := $(TOOLCHAIN_PREFIX)c++filt
SIZE := $(TOOLCHAIN_PREFIX)size

INCLUDES := -Iinclude
CFLAGS := -Os -g -mcpu=arm926ej-s -fno-builtin -W -Wall -Wno-multichar -Wno-unused-parameter
#CFLAGS += -Werror
CPPFLAGS := -fno-exceptions -fno-rtti -fno-threadsafe-statics
#CPPFLAGS := -Weffc++
LDFLAGS := 
LIBGCC := $(shell $(CC) $(CFLAGS) -print-libgcc-file-name)

CFLAGS += -ffunction-sections -fdata-sections
LDFLAGS += -gc-sections

all:: $(BUILDDIR)/$(TARGET) $(BUILDDIR)/$(TARGETELF).lst $(BUILDDIR)/$(TARGETELF).debug.lst $(BUILDDIR)/$(TARGETELF).sym

BOOTOBJS :=
KOBJS :=
OBJS :=
LINKER_SCRIPT := 

include arch/$(ARCH)/rules.mk
include platform/$(PLATFORM)/rules.mk
include kernel/rules.mk
#include os/rules.mk
include dev/rules.mk
include lib/rules.mk
#include tests/rules.mk

ALLOBJS := \
	$(BOOTOBJS) \
	$(KOBJS) \
	$(OBJS)

ALLOBJS := $(addprefix $(BUILDDIR)/,$(ALLOBJS))

DEPS := $(ALLOBJS:.o=.d)

$(BUILDDIR)/$(TARGET): $(BUILDDIR)/$(TARGETELF)
	$(SIZE) $<
	$(OBJCOPY) -O binary $< $@

$(BUILDDIR)/$(TARGETELF): $(ALLOBJS)
	$(LD) $(LDFLAGS) -T $(LINKER_SCRIPT) $(ALLOBJS) $(LIBGCC) -o $@

$(BUILDDIR)/$(TARGETELF).sym: $(BUILDDIR)/$(TARGETELF)
	$(OBJDUMP) -t $< | $(CPPFILT) > $@

$(BUILDDIR)/$(TARGETELF).lst: $(BUILDDIR)/$(TARGETELF)
	$(OBJDUMP) -Mreg-names-raw -d $< | $(CPPFILT) > $@

$(BUILDDIR)/$(TARGETELF).debug.lst: $(BUILDDIR)/$(TARGETELF)
	$(OBJDUMP) -Mreg-names-raw -S $< | $(CPPFILT) > $@

clean:
	rm -f $(ALLOBJS) $(DEPS) $(BUILDDIR)/$(TARGET) $(BUILDDIR)/$(TARGETELF) $(BUILDDIR)/$(TARGETELF).lst

spotless:
	rm -rf build-*

install: all
	scp $(BUILDDIR)/$(TARGET) 192.168.0.4:/tftproot

# makes sure the target dir exists
MKDIR = if [ ! -d $(dir $@) ]; then mkdir -p $(dir $@); fi

$(BUILDDIR)/%.o: %.c
	@$(MKDIR)
	@echo compiling $<
	@$(CC) $(CFLAGS) --std=c99 $(INCLUDES) -c $< -MD -MT $@ -MF $(@:%o=%d) -o $@

$(BUILDDIR)/%.o: %.cpp
	@$(MKDIR)
	@echo compiling $<
	@$(CC) $(CFLAGS) $(CPPFLAGS) $(INCLUDES) -c $< -MD -MT $@ -MF $(@:%o=%d) -o $@

$(BUILDDIR)/%.o: %.S
	@$(MKDIR)
	@echo compiling $<
	@$(CC) $(CFLAGS) $(INCLUDES) -c $< -MD -MT $@ -MF $(@:%o=%d) -o $@

# Empty rule for the .d files. The above rules will build .d files as a side
# effect. Only works on gcc 3.x and above, however.
%.d:

ifeq ($(filter $(MAKECMDGOALS), clean), )
-include $(DEPS)
endif
