.PHONY: all iso clean clean_work qemu check_mountpoints check_root

ISO_NAME := $(shell ls out/*.iso 2>/dev/null | sort -r | head -n 1)
ARCHISO_CMD := mkarchiso -v .

check_root:
	@if [ "$$(id -u)" -ne 0 ]; then \
		echo "Error: This script must be run as root (UID 0)."; \
		exit 1; \
	fi

check_mountpoints:
	@if mount | grep -q "$(shell realpath work)"; then \
		echo "Found mountpoints in work/. Unmounting..."; \
		sudo umount -R work/*; \
	fi

all: check_root clean_work iso

iso:
	$(ARCHISO_CMD)

clean: check_mountpoints
	rm -rf work/ out/

clean_work: check_mountpoints
	rm -rf work/

qemu: $(ISO_NAME)
	qemu-system-x86_64 --enable-kvm -smp $(shell echo $$(( `nproc` / 2 / 2 * 2 ))) -cpu host -m 4G -nic user -L /tmp --bios /usr/share/edk2-ovmf/x64/OVMF_CODE.fd -cdrom $(ISO_NAME)