CC      = gcc
AS      = as
LD      = ld
OBJCOPY = objcopy
CFLAGS  = -m32 -ffreestanding -fno-stack-protector -fno-pic -O2 -Wall -Wextra -std=gnu99 -mgeneral-regs-only
LDFLAGS = -m elf_i386 -z noexecstack -T src/linker.ld -nostdlib

all: kernel32.elf stage1.bin stage2.bin

boot.o: src/boot.S
	$(AS) --32 $< -o $@

kernel.o: src/kernel.c
	$(CC) $(CFLAGS) -c $< -o $@

stage1.o: src/stage1.S
	$(AS) --32 $< -o $@

stage1.bin: stage1.o
	$(LD) -m elf_i386 -Ttext=0x7c00 --oformat=binary -o stage1.raw $<
	python3 tools/mk_mbr.py stage1.raw $@
	rm -f stage1.raw
	@test `stat -c%s $@` -eq 512 || (echo "stage1.bin ist nicht 512 Byte"; exit 1)

stage2.o: src/stage2.S
	$(AS) --32 $< -o $@

stage2.bin: stage2.o
	$(LD) -m elf_i386 -Ttext=0x7e00 --oformat=binary -o $@ $<

stage1_blob.o: stage1.bin
	$(OBJCOPY) -I binary -O elf32-i386 -B i386 $< $@
	$(OBJCOPY) --rename-section .data=.rodata,alloc,load,readonly,data,contents $@

stage2_blob.o: stage2.bin
	$(OBJCOPY) -I binary -O elf32-i386 -B i386 $< $@
	$(OBJCOPY) --rename-section .data=.rodata,alloc,load,readonly,data,contents $@

hintergrund_blob.o: src/hintergrund.kbi
	$(OBJCOPY) -I binary -O elf32-i386 -B i386 $< $@
	$(OBJCOPY) --rename-section .data=.rodata,alloc,load,readonly,data,contents $@

kernel32.elf: boot.o kernel.o stage1_blob.o stage2_blob.o hintergrund_blob.o src/linker.ld
	$(LD) $(LDFLAGS) -o $@ boot.o kernel.o stage1_blob.o stage2_blob.o hintergrund_blob.o

clean:
	rm -f *.o *.bin kernel32.elf

.PHONY: all clean
