#! /bin/sh

##  Kernel-mode libcaca compilation script -- Sam Hocevar <sam@hocevar.net>

set -x
set -e

MYCFLAGS="-fno-builtin -O0 -I. -I.. -I../caca/ -Wall -D__KERNEL__ -fno-stack-protector -m32"

./configure --enable-kernel --disable-doc --host i386

# Compile cacademo, leave it as an object
cd caca && make && cd ..
cd examples && make dithering.o && cd ..

cd kernel

# Bootsector
nasm -f bin -o bootsect.bin boot/bootsect.asm
# Interruption handlers
nasm -f elf -o int.o boot/int.asm

##### Boot (x86)
# Stage2, loads GDT, PIC, IDT, interrupts, then calls kmain()
gcc $MYCFLAGS boot/stage2.c -c
# GDT installation, called by stage2
gcc $MYCFLAGS boot/gdt.c -c
# PIC installation, called by stage2
gcc $MYCFLAGS boot/pic.c -c
# IDT installation, called by stage2
gcc $MYCFLAGS boot/idt.c -c
# Interruptions installation, called by stage2
gcc $MYCFLAGS boot/interruptions.c -c

##### Drivers
# Floppy driver
gcc $MYCFLAGS drivers/floppy.c -c
# Processor driver
gcc $MYCFLAGS drivers/processor.c -c
# Keyboard handler
gcc $MYCFLAGS drivers/keyboard.c -c
# Memory driver
gcc $MYCFLAGS drivers/memory.c -c
# Programmable Interval Timer driver
gcc $MYCFLAGS drivers/timer.c -c

# Minimalistic libc
gcc $MYCFLAGS klibc.c -c

# Kernel by itself, contains cmain() which calls main()
gcc $MYCFLAGS kernel.c -c

# Link everything but bootsector, kernel.o MUST be at the very end
ld --oformat binary -Ttext 1000 stage2.o gdt.o pic.o int.o idt.o interruptions.o keyboard.o memory.o timer.o floppy.o processor.o klibc.o kernel.o ../caca/.libs/libcaca.a -Map kernel.map    -o kern.bin

ls -ail kern.bin
cd ..

# Copy bootsector at the very beginning of the floppy (first sector/512 bytes of the image), then kernel right after
cat kernel/bootsect.bin  kernel/kern.bin /dev/zero | dd of=cacademo.img bs=512 count=2500

