TARGETS = dusk
BOOTFS_SRC = fs/xcomp/boot.fs fs/lib/drivelo.fs fs/lib/str.fs fs/ar/tar.fs \
	fs/fs/tar.fs posix/fd.fs posix/glue.fs fs/xcomp/init.fs
ALLSRCS = $(shell find fs)
COS_UNITS = cos/core.fs cos/extra.fs
all: $(TARGETS)

blkpack: cos/blkpack.c
	$(CC) cos/blkpack.c -Wall -o $@

cos/extra.fs: # if it doesn't exist, create an file
	echo "( ----- 000 )" > $@

fs/cos/blk: $(COS_UNITS) blkpack
	cat $(COS_UNITS) | ./blkpack > $@

posix/boot.fs: $(BOOTFS_SRC)
	(echo init | cat $(BOOTFS_SRC) - ) > $@

posix/boot.h: posix/boot.fs
	./embedh.sh bootstring < posix/boot.fs > $@

posix/fs.tar: fs/cos/blk $(ALLSRCS)
	tar -cf $@ -C fs .

posix/fstar.h: posix/fs.tar
	./embedh.sh fstar < posix/fs.tar > $@

dusk: posix/vm.c posix/boot.h posix/fstar.h
	$(CC) posix/vm.c -Wall -o $@

usermode/dusk-stream:
	$(MAKE) -C usermode dusk-stream

.PHONY: testum
testum: usermode/dusk-stream
	cd usermode && echo " ' bye ABORTPTR ! f<< /tests/all.fs bye " | \
		./dusk-stream | tee /dev/stderr | grep "All tests passed"

bios13.img: fs/xcomp/i386/pc/bios13.fs
	echo "f<< /xcomp/i386/pc/bios13.fs org 512 dataout :write bye" | \
		./dusk 3> $@
	./bios13gen.sh >> $@

.PHONY: bios13run
bios13run: bios13.img
	# change "if" to "floppy" to if needed
	qemu-system-i386 -drive file=bios13.img,format=raw,index=0,if=ide

.PHONY: run
run: dusk
	stty -icanon -echo min 0; ./dusk ; stty icanon echo

.PHONY: test
test: dusk
	echo "' byefail ABORTPTR ! f<< tests/all.fs bye" | ./dusk || (echo; exit 1)

.PHONY: test6502
test6502: dusk
	echo "f<< /cos/6502.fs bye" | ./dusk || (echo; exit 1)

.PHONY: testcomp
testcomp: dusk
	echo "' byefail ABORTPTR ! f<< tests/comp/all.fs bye" | ./dusk || (echo; exit 1)

.PHONY: clean
clean:
	rm -f $(TARGETS) blkpack fs/cos/blk dusk.o posix/boot.fs \
		posix/fs.tar cos/extra.fs memdump *.bin *.img *.rom
