#
# Copyright (c) 2000 Blue Mug, Inc.  All Rights Reserved.
#

#
# Guarantee that the top-level TARGET variable, if set, is cs89712.
#
ifeq (,$(TARGET))
	TARGET := cs89712
endif
ifneq (cs89712,$(TARGET))
	error "building for cs89712 but TARGET != cs89712"
endif

#
# Configure settings based on the target passed from the top-level
# makefile.  The PROFILE := cdb89712 line is just a default and can
# be overridden from the command line.
#
PROFILE := cdb89712

ifneq (,$(wildcard profile-stamp))
	last-profile := $(shell cat profile-stamp)
	ifneq ($(PROFILE),$(last-profile))
		error := profile-error
	endif
endif

ifeq ($(PROFILE),cdb89712)
	SETTINGS := relocate standalone
endif
ifeq ($(PROFILE),cdb89712-boot)
	SETTINGS := bootmode standalone
endif
ifeq ($(PROFILE),cdb89712-kernel)
	SETTINGS := kernel standalone
endif

#
# Configuration for standalone, optimized ARM7TDMI cross-compile.
#
CROSS := arm-linux-
CC := $(CROSS)gcc
CFLAGS := -Wall -O2 -fomit-frame-pointer -I../../../include -nostdlib \
	-mcpu=arm7tdmi -static

#
# The LDSCRIPT variable can be overridden based on the target-derived
# settings.
#
LDSCRIPT := flash
OBJSECTIONS := .boot .text .data .bss
OBJCOPYFLAGS := -O binary -S $(addprefix -j ,$(OBJSECTIONS))

ASMS := boot.S
SRCS := entry.c eth.c flash_intel.c frob.c gunzip.c \
	linux.c loader.c medium.c memmap.c memzero.c

setp = $(if $(findstring $(1),$(SETTINGS)),y)

ifeq (y,$(call setp,bootmode))
	ASMS := init.S
	CFLAGS += -DBOOTMODE
	LDSCRIPT := bootmode
endif

ifeq (y,$(call setp,kernel))
	ASMS := init.S
	LDSCRIPT := kernel
endif

ifeq (y,$(call setp,relocate))
	CFLAGS += -DRELOCATE
endif

ifeq (y,$(call setp,standalone))
	CFLAGS += -DSTANDALONE
endif

OBJS := $(SRCS:.c=.o)
DEPS := $(SRCS:.c=.d)
LIBS := -lgcc -ltarget

all: $(error) profile-stamp loader-$(PROFILE).bin

profile-error:
	@echo "previous PROFILE:" `cat profile-stamp`
	@echo "profile-stamp mismatch; 'make scrub' to switch profiles"; false
profile-stamp:
	echo $(PROFILE) > $@

# can be invoked from top-level Makefile
download:
	shoehorn --terminal

# Hermit second stage loader (ELF image)
loader-$(PROFILE).elf: $(ASMS) $(OBJS) ../common/libtarget.a Makefile loader-$(PROFILE).lds
	$(CC) $(CFLAGS) -L. -L../common \
		-Wl,-Map,loader-$(PROFILE).map \
		-Wl,-Tloader-$(PROFILE).lds -o $@ \
		$(ASMS) $(OBJS) \
		-Wl,--start-group $(LIBS) -Wl,--end-group

loader-$(PROFILE).lds: $(wildcard loader.lds.*)
	cp loader.lds.$(LDSCRIPT) $@

%.bin: %.elf
	$(CROSS)objcopy $(OBJCOPYFLAGS) $< $@

# automated dependency checking
ifeq (,$(filter clean scrub,$(MAKECMDGOALS)))
include $(DEPS)

DEPENDS := ../../../depend.sh
%.d: %.c
	env CC=$(CC) $(DEPENDS) $< $@ $(CFLAGS)
endif

# installation
PHONY: install
install:
	$(INSTALL) -m 644 -o root -g root loader-$(PROFILE).bin \
		$(INSTALLPREFIX)/lib/hermit/

# housecleaning
.PHONY: clean
clean:
	rm -f $(OBJS) loader-*.lds *.elf *.bin *.map
scrub: clean
	rm -f profile-stamp *.d

