ifndef MAKECMDGOALS
  MAKECMDGOALS=none
endif

ifneq ($(MAKECMDGOALS),$(filter $(MAKECMDGOALS),clean distclean clean-doc doc))
  ifndef PLATFORM_DIR
    $(error please define PLATFORM_DIR 'make PLATFORM_DIR=foo')
  else
    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
  endif
endif

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
DOXYGEN    := doxygen

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 SYSCLK_FREQ
DEFS+= -DSYSCLK_FREQ=$(SYSCLK_FREQ)
endif

all: $(TARGET)

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

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

$(BUILD_DIR)/platform.dtb: $(DTS)
	$(ECHO) "[   DTC   ]     $(notdir $<)"
	${DTC} -O dtb -o $@ $< &> /dev/null

$(BUILD_DIR):
	$(MKDIR) $@

doc: Doxyfile
	$(DOXYGEN) Doxyfile

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

clean-doc:
	$(RM) doc

distclean: clean clean-doc

# =============================================================================
# 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:
