PROGRAMS = hello.com sys.com
KERNEL = @rdos.com
DISTFILES = $(KERNEL) $(PROGRAMS)

VERSION = $(shell git log -1 --format=%cd --date=format:%Y%m%d)
PRODUCT = rdos

QEMU = qemu-system-i386
QEMU_ARGS += $(shell test -w /dev/kvm && echo --enable-kvm)

METRIC = stat -c '%8s %n'

NASM = nasm
NASM_ARGS = -s -Isrc --before "cpu 8086" -DPRODUCT=$(PRODUCT) -DVERSION=$(VERSION)

ifndef DISPLAY
QEMU_ARGS += --display curses
endif

SYS = host/sys.elf

.PHONY: default clean qemu-floppy5 qemu-floppy3
.PRECIOUS: %.com

default: fd1440.img

# Host utils
host/%.elf: host/%.c
	$(CC) -o $@ $<

# COM programs
%.com: src/%.asm src/*.inc
	$(NASM) $(NASM_ARGS) -l $(@:.com=.lst) -o $@ $<
	$(METRIC) $@

# Bootloaders, first sector on partition
%.bs: boot/%.asm
	$(NASM) $(NASM_ARGS) -o $@ $<

@rdos.com: kernel/*.asm

# Special case: variations of FAT vbr
fat1.bs: boot/fat.asm
	$(NASM) $(NASM_ARGS) -DFAT12 -DCHS -o $@ $<

fat4.bs: boot/fat.asm
	$(NASM) $(NASM_ARGS) -DFAT16 -DCHS -o $@ $<

fat6.bs: boot/fat.asm
	$(NASM) $(NASM_ARGS) -DFAT16 -DCHS -DLARGE -o $@ $<

fd%.img: $(DISTFILES) $(SYS)
	mformat -C -i $@ -f $* -v "$(PRODUCT) $(VERSION)" ::
	mcopy      -i $@ $(DISTFILES) ::
	$(SYS)        $@ $(KERNEL)

hdd.img: mbr.bs $(KERNEL) fd1440.img
	dd if=mbr.bs bs=512 count=1 of=$@
	dd if=$(KERNEL) bs=512 seek=1 of=$@
	dd if=fd1440.img bs=512 seek=63 of=$@

clean:
	rm -f *.com *.bs *.0 *.lst *.img *.bin
	rm -f host/*.elf

qemu-floppy3: fd1440.img
	$(QEMU) $(QEMU_ARGS) -boot a -fda fd1440.img

qemu-floppy5: fd360.img
	$(QEMU) $(QEMU_ARGS) -boot a -fda fd360.img

qemu-hdd: hdd.img
	$(QEMU) $(QEMU_ARGS) -boot c -hda hdd.img

dosbox-%: %.com fd1440.img
	dosbox -c "mount P $(CURDIR)" -c P: -c "IMGMOUNT A: FD1440.IMG -t floppy" -c "$< $(ARGS)" -c pause -c exit

emu2-%: %.com
	emu2 $< $(ARGS)