# File author is Ítalo Lima Marconato Matias
# 
# Created on December 18 of 2017, at 11:14 BRST
# Last edited on December 27 of 2017, at 20:42 BRST
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

ARCH ?= x86
PREFIX ?= i686-elf-
VERBOSE ?= false

ifneq ($(VERBOSE),true)
NOECHO := @
endif

all: kernel-all build/chicago.iso

clean: kernel-clean
	$(NOECHO)rm -f build/chicago-$(ARCH).iso

clean-all: kernel-clean-all
	$(NOECHO)rm -rf build

remake: kernel-remake build/chicago-$(ARCH).iso

build/chicago-$(ARCH).iso: kernel/build/chkrnl-$(ARCH)
	$(NOECHO)echo Generating $@
	$(NOECHO)if [ ! -d $(dir $@) ]; then mkdir -p $(dir $@); fi
	$(NOECHO)if [ -d $(dir $@)/iso ]; then rm -rf $(dir $@)/iso; fi
	$(NOECHO)mkdir -p $(dir $@)/iso
	$(NOECHO)mkdir -p $(dir $@)/iso/boot
	$(NOECHO)mkdir -p $(dir $@)/iso/boot/grub
	$(NOECHO)cp kernel/build/chkrnl-$(ARCH) $(dir $@)/iso/boot/chkrnl
	$(NOECHO)echo 'set timeout=30' > $(dir $@)/iso/boot/grub/grub.cfg
	$(NOECHO)echo 'set default=0' >> $(dir $@)/iso/boot/grub/grub.cfg
	$(NOECHO)echo '' >> $(dir $@)/iso/boot/grub/grub.cfg
	$(NOECHO)echo 'menuentry "Boot from Hard Disk" {' >> $(dir $@)/iso/boot/grub/grub.cfg
	$(NOECHO)echo '    chainloader (hd0)+1' >> $(dir $@)/iso/boot/grub/grub.cfg
	$(NOECHO)echo '}' >> $(dir $@)/iso/boot/grub/grub.cfg
	$(NOECHO)echo '' >> $(dir $@)/iso/boot/grub/grub.cfg
	$(NOECHO)echo 'menuentry "CHicago Operating System" {' >> $(dir $@)/iso/boot/grub/grub.cfg
	$(NOECHO)echo '    multiboot /boot/chkrnl' >> $(dir $@)/iso/boot/grub/grub.cfg
	$(NOECHO)echo '    boot' >> $(dir $@)/iso/boot/grub/grub.cfg
	$(NOECHO)echo '}' >> $(dir $@)/iso/boot/grub/grub.cfg
ifdef ($(GRUB_DIR))
	$(NOECHO)grub-mkrescue -d $(GRUB_DIR) --output=$(dir $@)/chicago-$(ARCH).iso $(dir $@)/iso 1>/dev/null 2>/dev/null
else
	$(NOECHO)grub-mkrescue --output=$(dir $@)/chicago-$(ARCH).iso $(dir $@)/iso 2>/dev/null
endif
	$(NOECHO)rm -rf $(dir $@)/iso

kernel-all:
	$(NOECHO)VERBOSE=$(VERBOSE) ARCH=$(ARCH) PREFIX=$(PREFIX) $(MAKE) -C kernel all

kernel-clean:
	$(NOECHO)VERBOSE=$(VERBOSE) ARCH=$(ARCH) PREFIX=$(PREFIX) $(MAKE) -C kernel clean

kernel-clean-all:
	$(NOECHO)VERBOSE=$(VERBOSE) ARCH=$(ARCH) PREFIX=$(PREFIX) $(MAKE) -C kernel clean-all

kernel-remake:
	$(NOECHO)VERBOSE=$(VERBOSE) ARCH=$(ARCH) PREFIX=$(PREFIX) $(MAKE) -C kernel remake
