MKDOSFS = /sbin/mkdosfs
ISOLINUX_BIN = /usr/share/syslinux/isolinux.bin

all: boot.fs boot.iso

boot.iso: boot.dir
	mkisofs -o boot.iso -b isolinux.bin -c boot.cat -no-emul-boot -boot-load-size 4 -boot-info-table boot.dir

boot.fs: boot.dir
	-@mv ~/.mtoolsrc.appboxbak ~/.mtoolsrc >/dev/null 2>/dev/null
	-@mv ~/.mtoolsrc ~/.mtoolsrc.appboxbak >/dev/null 2>/dev/null
	rm -f boot.fs
	$(MKDOSFS) -C boot.fs $$[$(shell du -sk boot.dir | cut -f 1) + 512]
	echo -e 'drive m: file="'"$(shell pwd)/boot.fs"'"\nmtools_skip_check=1' > ~/.mtoolsrc
	mcopy boot.dir/* m:
	-@rm -f ~/.mtoolsrc
	-@mv ~/.mtoolsrc.appboxbak ~/.mtoolsrc >/dev/null 2>/dev/null
	syslinux boot.fs

boot.dir: boot.dir/vmlinuz boot.dir/initrd.img boot.dir/isolinux.cfg boot.dir/isolinux.bin boot.dir/syslinux.cfg

boot.dir/syslinux.cfg:
	echo 'DEFAULT appbox' > boot.dir/syslinux.cfg
	echo 'LABEL appbox' >> boot.dir/syslinux.cfg
	echo '    KERNEL vmlinuz' >> boot.dir/syslinux.cfg
	echo '    INITRD initrd.img' >> boot.dir/syslinux.cfg

boot.dir/isolinux.cfg: boot.dir/syslinux.cfg
	cp boot.dir/syslinux.cfg boot.dir/isolinux.cfg

boot.dir/isolinux.bin: $(ISOLINUX_BIN)
	cp $(ISOLINUX_BIN) boot.dir/isolinux.bin

boot.dir/vmlinuz: kernel/vmlinuz
	-mkdir boot.dir
	cp kernel/vmlinuz boot.dir/

boot.dir/initrd.img: kernel/modules initrd/init-earlyboot/init initrd/admin-tclkit/tclkit
	rm -rf __tmp__initrd
	mkdir __tmp__initrd
	cp -rp kernel/modules __tmp__initrd/
	cp initrd/init-earlyboot/init __tmp__initrd/
	cp initrd/admin-tclkit/tclkit __tmp__initrd/
	-mkdir boot.dir
	( cd __tmp__initrd; find . | cpio -H newc -o > ../__tmp__initrd.img )
	rm -rf __tmp__initrd
	gzip -9c __tmp__initrd.img > boot.dir/initrd.img
	rm -f __tmp__initrd.img

initrd/admin-tclkit/tclkit:
	$(MAKE) -C initrd/admin-tclkit

kernel/vmlinuz kernel/modules:
	$(MAKE) -C kernel vmlinuz modules

clean:
	rm -rf boot.dir __tmp__initrd
	rm -f boot.fs __tmp__initrd.img
	$(MAKE) -C kernel clean
	$(MAKE) -C initrd/admin-tclkit clean

distclean: clean
	$(MAKE) -C kernel distclean
	$(MAKE) -C initrd/admin-tclkit distclean

.PHONY: all clean distclean
