ifndef PLATFORM_DIR
$(error please define PLATFORM_DIR 'make PLATFORM_DIR=foo')
else

LD	       := mipsel-unknown-elf-ld
CC	       := mipsel-unknown-elf-gcc
AS	       := mipsel-unknown-elf-as
DU	       := mipsel-unknown-elf-objdump
RM	       := rm -rf
ECHO	   := echo
MKDIR	   := mkdir
DTC	       := dtc
HEXDUMP	   := hexdump

BUILD_DIR  := build
SRCS_DIR   := src
INCS_DIR   := include

# =============================================================================
# Include files paths
# =============================================================================

INCLUDE	   += -I. -I$(INCS_DIR) -I$(PLATFORM_DIR)

# =============================================================================
# Paths of sources in another directories
# =============================================================================

VPATH      += $(SRCS_DIR)
VPATH      += $(PLATFORM_DIR)

# =============================================================================
# Object files
# =============================================================================

CFLAGS     := -Wall -mno-gpopt -ffreestanding -fomit-frame-pointer -mips32 \
		      -ggdb -mlong-calls

C_SRCS	   := boot_elf_loader.c boot_ioc.c boot_memcpy.c boot_tty.c exceptions.c
ifndef SOCLIB
C_SRCS	   += sdcard.c spi.c
endif

S_SRCS	   := reset.S

OBJS       := $(subst .c,.o, $(notdir $(C_SRCS)))
OBJS       += $(subst .S,.o, $(notdir $(S_SRCS)))
OBJS       := $(addprefix $(BUILD_DIR)/, $(OBJS))

TARGET     := bin.soft

ifdef SOCLIB

DEFS+= -DSOCLIB_IOC
DTS=platform_soclib.dts
$(info Making for $(PLATFORM_DIR), SocLib variant)

else

DTS=platform_fpga.dts
$(info Making for $(PLATFORM_DIR), FPGA variant)

endif

ifdef SYSCLK_FREQ
DEFS+= -DSYSCLK_FREQ
endif


all: $(TARGET)

$(TARGET): $(BUILD_DIR) $(OBJS) conf/ldscript $(BUILD_DIR)/platform.ld
	$(ECHO) "[   LD   ]     $@"
	$(LD) -o $@ -T conf/ldscript $(OBJS)
	$(DU) -D $@ > $@.txt

$(BUILD_DIR)/platform.ld: $(BUILD_DIR)/platform.dtb
	$(HEXDUMP) -v -e '"BYTE(0x" 1/1 "%02X" ")\n"' $< > $@

$(BUILD_DIR)/platform.dtb: $(DTS)
	${DTC} -O dtb -o $@ $<

$(BUILD_DIR):
	$(MKDIR) $@

clean:
	$(RM) $(TARGET).txt $(TARGET) *~ $(BUILD_DIR)

distclean: clean

# =============================================================================
# Implicit makefile rules

$(BUILD_DIR)/%.o: %.c
	$(ECHO) "[   CC   ]     $(notdir $<)"
	$(CC) $(DEFS) $(CFLAGS) $(INCLUDE) -c -o $@ $<
	$(DU) -D $@ > $@.txt

$(BUILD_DIR)/%.o: %.S
	$(ECHO) "[   AS   ]     $(notdir $<)"
	$(CC) $(DEFS) ${INCLUDE} -g -mips32 -c -o $@ $<
	$(DU) -D $@ > $@.txt

.SILENT:
endif
