include makefile.inc

#CFLAGS  = -nostdlib -fno-exceptions -ffreestanding -fno-builtin -Wall -fno-stack-protector
CFLAGS  = -nostdlib -fno-exceptions -ffreestanding -fno-builtin -Wall
ASFLAGS = 
LFLAGS  = -T boot.ld -Map ${LIST}/boot.map --oformat binary
#LFLAGS  = -Ttext 0x1000 -Map ${LIST}/boot.map --oformat binary
BOOTA_LFLAGS = -Ttext 0x0 --oformat binary -nostdlib
BOOTM_LFLAGS = -Ttext 0x200 --oformat binary -nostdlib

#PTEST_LFLAGS = -Ttext 0x0 -Tdata 0x100 --oformat binary -nostdlib
PTEST_LFLAGS = -nostdlib

KERNEL  = ${BIN}/kernel.bin
ACIENT  = ${BIN}/boota.bin
MIDDLE  = ${BIN}/bootm.bin
FSBOOT  = ${BIN}/fsboot.bin
INIT	= ${INITDIR}/bin/ptest
INIT2	= ${INITDIR}/bin/ptest2

#for tools
KMKFS	= ${TOOLDIR}/bin/kmkfs
GETSIZE = ${TOOLDIR}/bin/getsize

#for test process
PTEST	= ${INITDIR}/bin/ptest
PTEST2	= ${INITDIR}/bin/ptest2

OBJS = $(subst .c,.o,$(wildcard *.c))

ASMSRC  = startup.S		\
		  sys_core.S    \
		  ihandlers.S	\
		  page_asm.S

ASMOBJS = $(ASMSRC:.S=.o)

HEADERS = $(wildcard *.h)

.PHONY: all
all : ${KERNEL} ${ACIENT} ${MIDDLE}
	cd usr; make
	@if [ ! -e ${FSBOOT} ];   \
	  then touch ${FSBOOT};   \
	fi
	${KMKFS} ${ACIENT} ${MIDDLE} ${KERNEL} ${FSBOOT} ${INIT} ${INIT2}

#${KERNEL} : ${ACIENT} ${MIDDLE} ${OBJS} ${ASMOBJS} boot.ld
#	${LD} ${LFLAGS} ${ACIENT} ${MIDDLE} ${OBJS} ${ASMOBJS} -o $@
${KERNEL} : ${OBJS} ${ASMOBJS} boot.ld
	${LD} ${LFLAGS} ${OBJS} ${ASMOBJS} -o $@

KSIZE=`${GETSIZE} ${KERNEL}`
${ACIENT} : bootacient.S ${KERNEL}
	echo ${KSIZE}
	${AS} --defsym KERNEL_SECTS=${KSIZE} bootacient.S -o bootacient.o -a > ${LIST}/boota.lst
	${LD} ${BOOTA_LFLAGS} bootacient.o -o $@

${MIDDLE} : bootmiddle.S
	${AS} bootmiddle.S -I ${INCLUDE} -o bootmiddle.o -a > ${LIST}/bootm.lst
	${LD} ${BOOTM_LFLAGS} bootmiddle.o -o $@

boot.ld: boot.ld.S
	$(CC) -E -P boot.ld.S -I $(INCLUDE) -o boot.ld 

%.o: %.S
	${AS} ${ASFLAGS} -I $(INCLUDE) -o $@ $<

%.o: %.c ${INCLUDE}/*.h ${INCLUDE}/sodex/*.h
	$(CC) -c ${CFLAGS} -I ${INCLUDE} -o $@ $<


.PHONY: tools
tools: ${KMKFS} ${GETSIZE}

${KMKFS} : ${TOOLDIR}/kmkfs.cpp
	$(C++) -o $@ ${TOOLDIR}/kmkfs.cpp
	chmod 755 $@

${GETSIZE} : ${TOOLDIR}/getsize.c
	$(CC) -o $@ ${TOOLDIR}/getsize.c
	chmod 755 $@


.PHONY: ptest
ptest : ${PTEST} ${PTEST2}
${PTEST} : ${INITDIR}/ptest.S
	$(AS) -o ptest.o ${INITDIR}/ptest.S
	$(LD) ${PTEST_LFLAGS} -o $@ ptest.o
${PTEST2} : ${INITDIR}/ptest2.S
	$(AS) -o ptest2.o ${INITDIR}/ptest2.S
	$(LD) ${PTEST_LFLAGS} -o $@ ptest2.o

.PHONY: clean
clean :
	rm ${OBJS} ${ASMOBJS} ${KERNEL} ${ACIENT} ${MIDDLE} ${KMKFS}
