# Programs
GCC	 = /usr/local/gcc-4.8.1-for-linux64/bin/x86_64-pc-linux-gcc
LD	 = /usr/local/gcc-4.8.1-for-linux64/bin/x86_64-pc-linux-ld
DD	 = dd
NASM = nasm

# Compiler / Linker Flags
# TODO: Finish when adding kernel development
NFLAGS_BOOT = -f bin -Ox
NFLAGS_GCC	= -f elf -Ox
CFLAGS = -c -std=c11 -march=i486 -mtune=generic -Wshadow -Wstrict-prototypes -m32 -Wall -Werror -O2 -ffreestanding -nostdinc -fno-strict-aliasing -fno-builtin -fno-stack-protector -fno-omit-frame-pointer -fno-common -I$(KERNEL_DIR) -fno-pic -fno-delete-null-pointer-checks -g
LFLAGS = -nostdlib --warn-common -nmagic -gc-sections -s -T $(KERNEL_DIR)/kernel_entry.ld -Map debug/kernel.map

# Directories
ROOT_DIR	= .
BOOT_DIR	= $(ROOT_DIR)/boot
BUILD_DIR	= $(ROOT_DIR)/build
KERNEL_DIR	= $(ROOT_DIR)/kernel

# Source Files
KERNEL_OBJECTS := $(patsubst %.s, %.o, $(wildcard $(KERNEL_DIR)/*.s)) $(patsubst %.c, %.o, $(wildcard $(KERNEL_DIR)/*.c $(KERNEL_DIR)/*/*.c))

# All / Actual Image
all: $(BUILD_DIR)/darkos.img
	
$(BUILD_DIR)/darkos.img: $(BOOT_DIR)/boot.bin $(BOOT_DIR)/krnldr.bin $(KERNEL_DIR)/kernel.bin
	# Make the build dir if it does not exist
	mkdir -p $(BUILD_DIR)
	
	$(DD) if=/dev/zero of=$@ bs=512 count=2880 conv=notrunc
	$(DD) if=$< of=$@ bs=512 conv=notrunc
	
	# TODO: Add this when copying files
	mkdir os-tmp/
	hdiutil mount -mountpoint os-tmp/ $@
	cp -i $(BOOT_DIR)/krnldr.bin os-tmp/
	cp -i $(KERNEL_DIR)/kernel.bin os-tmp/
	hdiutil detach os-tmp/
	rm -rf os-tmp/
	
	
# Source Code
vpath %.o $(KERNEL_DIR)

%.o: %.c
	$(GCC) $(CFLAGS) $< -o $@
	
%.o: %.s
	$(NASM) $(NFLAGS_GCC) $< -o $@ -I$(KERNEL_DIR)

%.bin: %.s
	$(NASM) $(NFLAGS_BOOT) $< -o $@
	
# Our kernel image
$(KERNEL_DIR)/kernel.bin: $(KERNEL_OBJECTS)
	$(LD) $(LFLAGS) $^ -o $@
	
	
# Running / Debugging
run: all
	qemu-system-i386 -fda $(BUILD_DIR)/darkos.img

debug: all
	qemu-system-i386 -fda $(BUILD_DIR)/darkos.img -s -S
	
	
# Cleaning
clean:
	rm -rf $(BOOT_DIR)/*.bin
	rm -rf $(BUILD_DIR)/*.img
	rm -rf $(KERNEL_DIR)/*.o
	rm -rf $(KERNEL_DIR)/*.bin