# Copyright 2022 John-Mark Gurney.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#

.if $(.OBJDIR) == $(.CURDIR)
.error Need to set MAKEOBJDIR.
.endif

.MAIN: all
.PHONY: all

PROGEXT = .elf

DEPENDS += .arm_deps

.for i in $(PROGS)
ALLTGTS+= $(i)$(PROGEXT) $(i).list $(i).sysinit
ASRCS.$(i) = $(SRCS) $(SRCS.$(i))
OBJS.$(i) = $(ASRCS.$(i):C/.c$/.o/)

ARM_DEP_SRCS+= $(ASRCS.$(i))

$(i)$(PROGEXT) $(i).map: $(OBJS.$(i))
	$(ARMCC) $(ARMTARGET) -o $(i)$(PROGEXT) $(.ALLSRC) -T$(LINKER_SCRIPT) --specs=nosys.specs -Wl,-Map="$(i).map" -Wl,--gc-sections -static --specs=nano.specs -Wl,--start-group -lc -lm -Wl,--end-group

$(i).sysinit: $(ASRCS.$(i))
	grep ^SYSINIT $(.ALLSRC) | sort -k 2 -k 3 > $@ || (rm -f $@ && false)

$(i).list: $(i)$(PROGEXT)
	$(ARMOBJDUMP) -h -S $(.ALLSRC) > $@ || (rm -f $@ && false)
.endfor

.PHONY: depend
depend: $(DEPENDS)

.arm_deps: $(ARM_DEP_SRCS)

.arm_deps:
	$(ARMCC) $(ARMTARGET) $(CFLAGS) $(.ALLSRC) -MM > $@ || (rm -f $@ && false)

.for i in $(DEPENDS)
.sinclude "$i"
.endfor

all: $(ALLTGTS)

.PHONY: runbuild
runbuild: $(SRCS) Makefile mk/*.mk
	for i in $(EXTRA_DEPENDS) $(.MAKEFILE_LIST) $(.ALLSRC) $$(cat $(DEPENDS) | gsed ':x; /\\$$/ { N; s/\\\n//; tx }' | sed -e 's/^[^:]*://'); do if [ "$$i" != ".." ]; then echo $$i; fi; done | sort -u | entr -d sh -c 'echo starting...; cd $(.CURDIR) && $(MAKE) $(.MAKEFLAGS) depend && $(MAKE) $(.MAKEFLAGS) all'

# native objects
.SUFFIXES: .no
.c.no:
	$(CC) $(CFLAGS) -c $< -o $@

.c.o:
	$(ARMCC) $(ARMTARGET) $(CFLAGS) -c $< -o $@