BOOTIMAGE= ../server/hello/hello
#BOOTIMAGE= ../../linux/glinux

include ../Makeconf

ifneq ($(wildcard $(BOOTIMAGE)),)

BOOTIMAGE_ENTRY := $(shell objdump --file-headers $(BOOTIMAGE) | grep '^start address' | cut -f3 -d' ')
BOOTIMAGE_START := $(shell file $(BOOTIMAGE) | grep -q ELF && $(SIZE) --format=sysv --radix=16 $(BOOTIMAGE) | grep ^.text | awk '{printf "0x%s", $$3}' || (echo Warning: BOOTIMAGE is a.out, guessing BOOTIMAGE_START from BOOTIMAGE_ENTRY 1>&2; echo '($(BOOTIMAGE_ENTRY)&~0xfff)'))
BOOTIMAGE_END =   $(BOOTIMAGE_START)+$(shell $(SIZE) $(BOOTIMAGE) | tail -1 | awk '{print $$4}')
BOOTIMAGE_SP = $(BOOTIMAGE_END)

BOOTIMAGE_DEP = $(BOOTIMAGE)

endif

SUBDIRS= src boot/floppy boot/grub

.PHONY: all
all: src diskboot grubboot

l4kernel: src/l4.exe Makefile $(BOOTIMAGE_DEP)
	dd bs=512 if=$< skip=1 of=$@
ifneq ($(wildcard $(BOOTIMAGE)),)
	@echo Using BOOTIMAGE=\"$(BOOTIMAGE)\"
	perl support/binpatch $@ 0x1040 4 "$(BOOTIMAGE_SP)"
	perl support/binpatch $@ 0x1044 4 "$(BOOTIMAGE_ENTRY)"
	perl support/binpatch $@ 0x1048 4 "$(BOOTIMAGE_START)"
	perl support/binpatch $@ 0x104c 4 "$(BOOTIMAGE_END)"
	perl support/binpatch $@ 0x1080 4 "$(BOOTIMAGE_START)"
	perl support/binpatch $@ 0x1084 4 "$(BOOTIMAGE_END)"

	perl support/binpatch $@ 0x1070 4 0	# RESERVED_MEM1_LOW
	perl support/binpatch $@ 0x1074 4 0	# RESERVED_MEM1_HIGH
	perl support/binpatch $@ 0x1088 4 0	# DEDICATED_MEM2_LOW
	perl support/binpatch $@ 0x108c 4 0	# DEDICATED_MEM2_HIGH
	perl support/binpatch $@ 0x1090 4 0	# DEDICATED_MEM3_LOW
	perl support/binpatch $@ 0x1094 4 0	# DEDICATED_MEM3_HIGH
	perl support/binpatch $@ 0x1098 4 0	# DEDICATED_MEM4_LOW
	perl support/binpatch $@ 0x109c 4 0	# DEDICATED_MEM4_HIGH
else
	@echo Warning: BOOTIMAGE=\"$(BOOTIMAGE)\" not found 1>&2
endif

src/l4.exe: src

diskboot.img diskboot: l4kernel boot/floppy

grubboot.img grubboot: l4kernel boot/grub

.PHONY: src boot/floppy boot/grub
src boot/floppy boot/grub:
	cd $@ && $(MAKE) all

.PHONY: clean
clean::
	for i in $(SUBDIRS) ; do \
	    ( cd $$i && $(MAKE) $@ ) || exit 1; \
	  done

clean::
	rm -f l4kernel
