# =============================================================================
# \file      Makefile
# \author    Cesar Fuguet
# \date      July 9, 2014
# =============================================================================
include ../common.mk

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

CONFDIR ?= output
CONF    := $(addprefix $(CONFDIR)/config/, hard_config.h)

INCLUDE += -I$(CONFDIR)/config

# =============================================================================
# Utils library
# =============================================================================

LIB_SRCS   := stdio.c            \
              string.c           \
              tty.c              \
              simhelper.c

LIB_OBJS   := $(addprefix $(BUILD_DIR)/,\
                  $(subst .c,.o, $(notdir $(LIB_SRCS))))

LIB_TARGET := $(BUILD_DIR)/libutils.a

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

S_SRCS := reset.S
C_SRCS := main.c

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

TARGET := $(BUILD_DIR)/soft.elf

# =============================================================================
# Test variables
# =============================================================================
PLATFORM  := ../../../../../platforms/tsar_generic_iob
SIMULATOR := $(PLATFORM)/simul.x

# batch mode => no xterm or frame buffer windows
SOCLIB_TTY := FILES
SOCLIB_FB  := HEADLESS
SOCLIB_GDB ?=
export SOCLIB_TTY SOCLIB_FB SOCLIB_GDB

# =============================================================================
# Makefile rules
# =============================================================================

all: $(TARGET)

# Specific dependencies
# NOTE: normal prerequisites | order-only prerequisites
# SEE: http://www.gnu.org/software/make/manual/make.html#Prerequisite-Types

$(LIB_OBJS): $(CONF) | $(BUILD_DIR)
$(OBJS): $(CONF) | $(BUILD_DIR)

$(LIB_TARGET): $(LIB_OBJS)
	$(AR) rcs $@ $(LIB_OBJS)

$(TARGET): $(OBJS) ../soft.ld $(LIB_TARGET)
	$(LD) -o $@ -T ../soft.ld $(OBJS) -L$(BUILD_DIR) -lutils
	$(DU) -D $@ > $@.txt

test: $(SIMULATOR) $(TARGET)
	-$< -SOFT $(TARGET) -DISK /dev/null 2> /dev/null >> $(CONFDIR)/log
	-soclib-cleanup-terms &> /dev/null
	mv term0 $(CONFDIR)/term
	grep -q "success" $(CONFDIR)/term
	if [ $$? == 0 ]; then \
		echo $$(basename $(PWD)) ": Success"; \
	else \
		echo $$(basename $(PWD)) ": Failure"; \
	fi;

$(SIMULATOR) $(CONF): $(PLATFORM)/scripts/onerun.py
	./$< -o $(CONFDIR) -p $(PLATFORM) -x1 -y1 -n1 -c

$(BUILD_DIR):
	$(MKDIR) $@

clean:
	$(RM) $(BUILD_DIR)

clean-log:
	$(RM) $(CONFDIR)

distclean: clean clean-log
