# $1 Title
# $2... Kernel cmdline
function add_entry {
	menuentry "OS_TITLE VER $1" "$@" --class android-x86 {
		shift 2
		savedefault
		set root=$android
		linux $kdir/kernel CMDLINE $src $@
		initrd $kdir/initrd.img
	}
}

# $1 EFI to chainload
# $2 OS name
# $3 Class
function add_os_if_exists {
	# Is there a better way to find ESP?
	for d in hd0,gpt1 hd0,gpt2 hd1,gpt1 hd1,gpt2 hd0,msdos1 hd0,msdos2 hd1,msdos1 hd1,msdos2; do
		if [ "($d)$1" != "$cmdpath/$bootefi" -a -e ($d)$1 ]; then
			menuentry "$2 at $d ->" "$d" "$1" --class "$3" {
				savedefault
				set root=$2
				chainloader ($root)$3
			}
			break
		fi
	done
}

function savedefault {
	if [ -s $prefix/grubenv -a "$chosen" != "$default" ]; then
		set default="$chosen"
		save_env default
	fi
}

function load_theme {
	loadfont DejaVuSansMono-18
	set gfxmode=1024x768
	terminal_output gfxterm
	set theme=$prefix/theme/theme.txt
	export theme
}

if [ -s $prefix/theme/theme.txt ]; then
	load_theme
fi

if [ -s $prefix/grubenv ]; then
	load_env
fi

if [ "$grub_cpu" = "i386" ]; then
	set bootefi=bootia32.efi
	set grub=grubia32
else
	set bootefi=BOOTx64.EFI
	set grub=grubx64
fi

if [ -z "$src" -a -n "$isofile" ]; then
	set src=iso-scan/filename=$isofile
fi

search --no-floppy --set android -f $kdir/kernel
export android bootefi grub kdir live src

# Create main menu
add_entry "$live" quiet
add_entry "$debug_mode" DEBUG=2
if [ -s ($android)$kdir/install.img ]; then
	add_entry "Installation" INSTALL=1
fi

submenu "Advanced options -> " --class forward {
	add_entry "$live - No Setup Wizard" quiet SETUPWIZARD=0
	add_entry "$live - No Hardware Acceleration" quiet nomodeset HWACCEL=0
	if [ -s ($android)$kdir/install.img ]; then
		add_entry "Auto Install to specified harddisk" AUTO_INSTALL=0
		add_entry "Auto Update" AUTO_INSTALL=update
	fi
	add_os_if_exists /EFI/BOOT/$bootefi "UEFI OS" os
	add_os_if_exists /EFI/BOOT/fallback.efi "UEFI Fallback" os
	add_os_if_exists /EFI/BOOT/fallback_x64.efi "UEFI Fallback" os
	menuentry "Reboot" --class reboot { reboot }
	menuentry "Poweroff" --class shutdown { halt }
	menuentry "UEFI firmware settings" --class setup { fwsetup }
}

# Add other OSes boot loaders if exist
add_os_if_exists /EFI/fedora/${grub}.efi Fedora fedora
add_os_if_exists /EFI/centos/${grub}.efi CentOS centos
add_os_if_exists /EFI/ubuntu/${grub}.efi Ubuntu ubuntu
add_os_if_exists /EFI/debian/${grub}.efi Debian debian
add_os_if_exists /EFI/gentoo/${grub}.efi Gentoo gentoo
add_os_if_exists /EFI/opensuse/${grub}.efi openSUSE opensuse
add_os_if_exists /EFI/linuxmint/${grub}.efi "Linux Mint" linuxmint
add_os_if_exists /EFI/boto/bootx64.efi OPENTHOS openthos
add_os_if_exists /EFI/Microsoft/Boot/bootmgfw.efi Windows windows

for d in $config_directory $cmdpath $prefix; do
	if [ -f $d/custom.cfg ]; then
		source $d/custom.cfg
	fi
done
