#!/bin/bash
# Author: Steven Shiau <steven _at_ clonezilla org>
# License: GPL
# Description: This program will put a syslinux.cfg or isolinux.cfg in target directory, which is used to boot clonezilla live.

#
DRBL_SCRIPT_PATH="${DRBL_SCRIPT_PATH:-/usr/share/drbl}"

. $DRBL_SCRIPT_PATH/sbin/drbl-conf-functions
. /etc/drbl/drbl-ocs.conf
. $DRBL_SCRIPT_PATH/sbin/ocs-functions

# Settings
KERNEL_FILE_DEFAULT="live/$kernel_file"
INITRD_FILE_DEFAULT="live/$initrd_file"
# default time (Unit: 1/10 secs)
TIMEOUT_DEF="300"
# Grub config
# root default is (hd0,0), root for Linux in bootparam is default as /dev/sda1 (root=/dev/sda1)
OP_HD_DEV_GRUB_DEF="hd0"
OP_PART_NO_GRUB_DEF="0"
OUTPUT_DEV_GRUB_DEF="/dev/sda1"
OUTPUT_TITLE_DEF="Clonezilla live"
GPARTED_LIVE_MAINTAINER="Steven Shiau"
# ocs_logo_img_png is loaded from drbl.conf
BGIMG_FILE_DEF="$ocs_logo_img_png"
#
quiet_opt=""
# By default we use nosplash.
splash_opt="nosplash"
# The flag about dark or light background
background_mode="light"
# By default toram_mode is only filesystem.squashfs (compact). The mode "live" is for copying the whole "live" directory, and the mode "all" is for whole files for the live system.
TORAM_MODE_DEF="compact"
enable_speech="no"
beep_ascii=""

#
prog="$(basename $0)"

# functions
USAGE() {
    echo "Usage:"
    echo "To create syslinux or isolinux menu for clonezilla live:"
    echo "$prog [OPTION] [isolinux|syslinux|grub-efi|grub2-efi|grub2-efi-ia32|grub2-efi-x64] OUTPUT-DIR" 
    echo "OPTION:"
    language_help_prompt_by_idx_no
    echo "-a, --splash                       Assign boot parameter 'splash'"
    echo "-b, --bg-mode  [text|graphic]      Assign the back ground of boot menu. Default is graphic"
    echo "-c, --toram-mode  MODE             Assign the mode for \"To RAM\" boot menu. Available modes are \"compact\", \"live\" and \"all\". \"compact\" will copy filesystem.squashfs only, \"live\" will copy the directory \"live\", and \"all\" will copy all the files in the live partition to RAM."
    echo "-d, --dark-bg                      Assign the dark background. The prompt text will use be the brighter on. By default we use lighter background."
    echo "-f, --framebuffer-mode  VGA_MODE   Assign the framebuffer mode as VGA_MODE, for example, 788 is resolution 800x600 with 16 bpp."
    echo "-k, --kernel-file FILENAME         Provide the kernel name, which wiil be used in the menu.lst or syslinux.cfg. If unset, $KERNEL_FILE_DEFAULT will be used" 
    echo "-i, --initrd-file FILENAME         Provide the initrd name, which wiil be used in the menu.lst or syslinux.cfg. If unset, $INITRD_FILE_DEFAULT will be used" 
    echo "-j, --enable-speech  Enable the boot menu for speech synthesis"
    echo "-n, --version-no VER_no            Provide the version number to be shown in the syslinux/isolinux boot menu."
    echo "-p, --boot-param  PARAM            Provide the append strings for kernel bootparam. which wiil be used in the menu.lst or syslinux.cfg. If unset, $BOOT_PARAM_DEFAULT will be used. Note! For clonezilla live (based on Debian Live), boot=casper or boot=live is a must, so do not forget to include it." 
    echo "-g1, grub-hd-dev DEV     Assign grub root device DEV (Ex: hd0)"
    echo "-g2, grub-part-no NO     Assign grub root partition number index NO (Ex: 0)"
    echo "-g3, OS-root-dev ROOTDEV Assign ROOTDEV which grub will pass as boot param (Ex. /dev/sda1)"
    echo "-s, --show-only-one-vga  Show only one default VGA mode. By default, we will show 3 modes (1024x768, 800x600 and 640x480). If this is set, only the mode assigned by option -f|--framebuffer-mode will be shown. If you do not assign the mode by option -f|--framebuffer-mode, the default one ($VGA_MODE_DEF) will be shown."
    echo "-sp, --splash      Add 'splash' in the boot parameter."
    echo "-u, --use-uvesafb  Use uvesafb mode instead of vesafb (mode should be set according to the kernel support)."
    echo "-t, --timeout TIME   Assign TIME*0.1 secs for timeout when booting."
    echo "-e, --title TITLE    Assign boot menu title (Clonezilla live, DRBL/Clonezilla server live...), default is 'Clonezilla live'."
    echo "-m, --bgimg IMG      Assign boot menu title background as IMG file (absolute file, 640x480 image.)"
    echo "-r, --extraprompt TXT  Add the TXT as the extra prompt on the boot menu prompt."
    echo "-q, --quiet          Assign boot parameter 'quiet'"
    echo "-vb, --vga-blacklist Enable the VGA blacklist"
    echo "-z, --add-lang-menu LANG   Add locale LANG menu in boot menu"
    echo "Ex:"
    echo "To create a isolinux menu in dir isolinux_tmp/isolinux/"
    echo "$prog isolinux isolinux_tmp/isolinux/"
    echo "To create a grub2 EFI menu in dir grub_tmp/boot/grub/"
    echo "$prog grub2-efi grub_tmp/boot/grub/"
}
gen_config_syslinux() {
  local type=$1
  case "$type" in
    isolinux) output_file="$output_dir/isolinux.cfg" ;;
    syslinux) output_file="$output_dir/syslinux.cfg" ;;
  esac
  bg_img="$(basename $bgimg_file)"
  echo "Adding $type menus for $output_title..."
  cat <<-BOOT_MENU_END > $output_file
# Created by generate-pxe-menu! Do NOT edit unless you know what you are doing! 
# Keep those comment "MENU DEFAULT" and "MENU HIDE"! Do NOT remove them.
# Note!!! If "serial" directive exists, it must be the first directive
default $MENUC32
timeout $timeout
prompt 0
noescape 1
MENU MARGIN 5
$mask MENU BACKGROUND $bg_img
# Set the color for unselected menu item and timout message
BOOT_MENU_END

if [ "$background_mode" = "dark" ]; then
  cat <<-BOOT_MENU_END >> $output_file
$mask MENU COLOR TITLE    1;36;44    #ffffffff #00000000
$mask MENU COLOR SEL      7;37;40    #FF000000 #FFC0C0C0
$mask MENU COLOR HOTSEL   1;7;37;40  #FF000000 #FFC0C0C0

BOOT_MENU_END
else
  cat <<-BOOT_MENU_END >> $output_file
$mask MENU COLOR UNSEL 7;32;41 #c0000090 #00000000
$mask MENU COLOR TIMEOUT_MSG 7;32;41 #c0000090 #00000000
$mask MENU COLOR TIMEOUT 7;32;41 #c0000090 #00000000
$mask MENU COLOR HELP 7;32;41 #c0000090 #00000000

BOOT_MENU_END
fi

  cat <<-BOOT_MENU_END >> $output_file
# MENU MASTER PASSWD

say **********************************************************************
say $boot_menu_txt_say_pkg
say $boot_menu_txt_say_org
say $project_url
say THIS SOFTWARE COMES WITH ABSOLUTELY NO WARRANTY! USE AT YOUR OWN RISK!$beep_ascii
say **********************************************************************

# Allow client to edit the parameters
ALLOWOPTIONS 1

# simple menu title
MENU TITLE $project_url

# Since no network setting in the squashfs image, therefore if ip=, the network is disabled. That's what we want.
label $output_title
  MENU DEFAULT
  # MENU HIDE
  MENU LABEL $output_title ($vga_default_prompt)
  # MENU PASSWD
  kernel $kernel_file
  append initrd=$initrd_file $boot_param $vga_default_mode ip= net.ifnames=0 $quiet_opt $splash_opt $vga_blacklist_opt
  TEXT HELP
  $extraprompt
  $boot_menu_pkg_ver_cpright
  $boot_menu_pkg_disclaimer
  ENDTEXT

label $output_title (To RAM)
  # MENU DEFAULT
  # MENU HIDE
  MENU LABEL $output_title ($vga_default_prompt & To ^RAM)
  # MENU PASSWD
  kernel $kernel_file
  append initrd=$initrd_file $boot_param $vga_default_mode $toram_opt ip= net.ifnames=0 $quiet_opt $splash_opt $vga_blacklist_opt
  TEXT HELP
  All the programs will be copied to RAM, so you can
  remove boot media (CD or USB flash drive) later
  ENDTEXT

label $output_title HiDPI
  # MENU DEFAULT
  # MENU HIDE
  MENU LABEL $output_title (VGA with ^large font & To RAM)
  # MENU PASSWD
  kernel $kernel_file
  append initrd=$initrd_file $boot_param nomodeset $toram_opt ip= net.ifnames=0 $quiet_opt $splash_opt live_console_font_size=16x32
  TEXT HELP
  Large font, all the programs will be copied to RAM, so you can
  remove boot media (CD or USB flash drive) later
  ENDTEXT

BOOT_MENU_END

# speech synthesis
if [ "$enable_speech" = "yes" ]; then
cat <<-BOOT_MENU_END >> $output_file
label $output_title speech synthesis
  # MENU DEFAULT
  # MENU HIDE
  MENU LABEL $output_title with ^speech synthesis
  # MENU PASSWD
  kernel $kernel_file
  append initrd=$initrd_file $boot_param $vga_default_mode ip= net.ifnames=0 $quiet_opt $splash_opt $vga_blacklist_opt speakup.synth=soft ---
  TEXT HELP
  $extraprompt
  $boot_menu_pkg_ver_cpright
  $boot_menu_pkg_disclaimer
  ENDTEXT

BOOT_MENU_END
fi

echo "MENU BEGIN Other modes of $output_title" >> $output_file

if [ "$show_vga_mode" = "3" ]; then
  cat <<-BOOT_MENU_END >> $output_file
label $output_title 1024x768
  # MENU DEFAULT
  # MENU HIDE
  MENU LABEL $output_title ($vga_1024x768_prompt)
  # MENU PASSWD
  kernel $kernel_file
  append initrd=$initrd_file $boot_param $vga_mode_1024x768 ip= net.ifnames=0 $quiet_opt $splash_opt $vga_blacklist_opt
  TEXT HELP
  VGA mode 1024x768. OK for most of VGA cards.
  ENDTEXT

label $output_title 640x480
  # MENU DEFAULT
  # MENU HIDE
  MENU LABEL $output_title ($vga_640x480_prompt)
  # MENU PASSWD
  kernel $kernel_file
  append initrd=$initrd_file $boot_param $vga_mode_640x480 ip= net.ifnames=0 $quiet_opt $splash_opt $vga_blacklist_opt
  TEXT HELP
  VGA mode 640x480. OK for most of VGA cards.
  ENDTEXT

BOOT_MENU_END
fi

cat <<-BOOT_MENU_END >> $output_file
label $output_title KMS
  # MENU DEFAULT
  # MENU HIDE
  MENU LABEL $output_title (^KMS)
  # MENU PASSWD
  kernel $kernel_file
  append initrd=$initrd_file $boot_param_rm_nomodeset $vga_mode_1024x768 ip= net.ifnames=0 $quiet_opt $splash_opt
  TEXT HELP
  KMS mode. OK for ATI, Intel and NVIDIA VGA cards.
  ENDTEXT

label $output_title KMS & To RAM
  # MENU DEFAULT
  # MENU HIDE
  MENU LABEL $output_title (KMS & To RAM)
  # MENU PASSWD
  kernel $kernel_file
  append initrd=$initrd_file $boot_param_rm_nomodeset $vga_mode_1024x768 $toram_opt ip= net.ifnames=0 $quiet_opt $splash_opt
  TEXT HELP
  KMS mode. OK for ATI, Intel and NVIDIA VGA cards.
  ENDTEXT

label $output_title KMS, To RAM & large font
  # MENU DEFAULT
  # MENU HIDE
  MENU LABEL $output_title (KMS with ^large font & To RAM)
  # MENU PASSWD
  kernel $kernel_file
  append initrd=$initrd_file $boot_param_rm_nomodeset $vga_mode_1024x768 $toram_opt ip= net.ifnames=0 $quiet_opt $splash_opt live_console_font_size=16x32
  TEXT HELP
  KMS mode. OK for ATI, Intel and NVIDIA VGA cards.
  ENDTEXT

BOOT_MENU_END

if [ -n "$lang_locale" ]; then
  cat <<-BOOT_MENU_END >> $output_file
label $output_title ($lang_locale)
  # MENU DEFAULT
  # MENU HIDE
  MENU LABEL $output_title ($lang_locale, default settings$vga_default_prompt)
  # MENU PASSWD
  kernel $kernel_file
  append initrd=$initrd_file $boot_param $vga_default_mode locale=$lang_locale ip= net.ifnames=0 $quiet_opt $splash_opt $vga_blacklist_opt
  TEXT HELP
  $lang_locale, and VGA mode 1024x768
  ENDTEXT

BOOT_MENU_END
if [ "$show_vga_mode" = "3" ]; then
  cat <<-BOOT_MENU_END >> $output_file
label $output_title ($lang_locale) 1024x768
  # MENU DEFAULT
  # MENU HIDE
  MENU LABEL $output_title ($lang_locale, default settings$vga_1024x768_prompt)
  # MENU PASSWD
  kernel $kernel_file
  append initrd=$initrd_file $boot_param $vga_mode_1024x768 locale=$lang_locale ip= net.ifnames=0 $quiet_opt $splash_opt $vga_blacklist_opt
  TEXT HELP
  $lang_locale, and VGA mode 1024x768.
  ENDTEXT

label $output_title ($lang_locale) 640x480
  # MENU DEFAULT
  # MENU HIDE
  MENU LABEL $output_title ($lang_locale, default settings$vga_640x480_prompt)
  # MENU PASSWD
  kernel $kernel_file
  append initrd=$initrd_file $boot_param $vga_mode_640x480 locale=$lang_locale ip= net.ifnames=0 $quiet_opt $splash_opt $vga_blacklist_opt
  TEXT HELP
  $lang_locale, and VGA mode 640x480. OK for most of VGA cards, 
  Choose this if this is an Asus Eee PC
  ENDTEXT

BOOT_MENU_END
fi
  cat <<-BOOT_MENU_END >> $output_file
label $output_title ($lang_locale) KMS
  # MENU DEFAULT
  # MENU HIDE
  MENU LABEL $output_title ($lang_locale, default settings, KMS)
  # MENU PASSWD
  kernel $kernel_file
  append initrd=$initrd_file $boot_param_rm_nomodeset $vga_mode_1024x768 locale=$lang_locale ip= net.ifnames=0 $quiet_opt $splash_opt
  TEXT HELP
  $lang_locale, and KMS mode.
  ENDTEXT

label $output_title ($lang_locale. To RAM)
  # MENU DEFAULT
  # MENU HIDE
  MENU LABEL $output_title ($lang_locale. To RAM. Boot media can be removed later)
  # MENU PASSWD
  kernel $kernel_file
  append initrd=$initrd_file $boot_param $vga_default_mode locale=$lang_locale $toram_opt ip= net.ifnames=0 $quiet_opt $splash_opt $vga_blacklist_opt
  TEXT HELP
  $lang_locale, and alll the programs will be copied to RAM,
  so you can remove boot media (CD or USB flash drive) later
  ENDTEXT

BOOT_MENU_END
fi

  cat <<-BOOT_MENU_END >> $output_file
label $output_title without framebuffer
  # MENU DEFAULT
  # MENU HIDE
  MENU LABEL $output_title (Safe graphic settings, vga=normal)
  # MENU PASSWD
  kernel $kernel_file
  append initrd=$initrd_file $boot_param ip= net.ifnames=0 nomodeset vga=normal nosplash
  TEXT HELP
  Disable console frame buffer support
  ENDTEXT

label $output_title failsafe mode
  # MENU DEFAULT
  # MENU HIDE
  MENU LABEL $output_title (Failsafe mode)
  # MENU PASSWD
  kernel $kernel_file
  append initrd=$initrd_file $boot_param acpi=off irqpoll noapic noapm nodma nomce nolapic nosmp ip= net.ifnames=0 nomodeset vga=normal nosplash
  TEXT HELP
  acpi=off irqpoll noapic noapm nodma nomce nolapic 
  nosmp nomodeset vga=normal nosplash
  ENDTEXT

BOOT_MENU_END
echo "MENU END" >> $output_file

cat <<-BOOT_MENU_END >> $output_file
label local
  # MENU DEFAULT
  # MENU HIDE
  MENU LABEL Local operating system in harddrive (if available)
  # MENU PASSWD
  # 2 method to boot local device:
  # (1) For localboot 0, it is decided by boot order in BIOS, so uncomment the follow 1 line if you want this method:
  # localboot 0

  # (2) For chain.c32, you can assign the boot device.
  # Ref: extlinux.doc from syslinux
  # Syntax: APPEND [hd|fd]<number> [<partition>]
  # [<partition>] is optional.
  # Ex:
  # Second partition (2) on the first hard disk (hd0);
  # Linux would *typically* call this /dev/hda2 or /dev/sda2, then it's "APPEND hd0 2"
  #
  kernel chain.c32
  append hd0
  TEXT HELP
  Boot local OS from first hard disk if it's available
  ENDTEXT

BOOT_MENU_END

# If both memtest and fdos exist, group them
if [ -n "$(ls -l $tmp_sys_files_path/mt86+x*.mbr 2>/dev/null)" ] && \
   [ -e "$tmp_sys_files_path/freedos.img" ]; then
  echo "MENU BEGIN Memtest & FreeDOS" >> $output_file
fi

# For memtest86+ in legacy BIOS:
# memtest86+.bin -> mt86+x32.mbr
# memtest86+x32.bin -> mt86+x32.mbr
# memtest86+ia32.bin -> mt86+x32.mbr
# memtest86+x64.bin -> mt86+x64.mbr
if [ -e "$tmp_sys_files_path/mt86+x32.mbr" ]; then
  cat <<-BOOT_MENU_END >> $output_file

# Note! *.bin is specially purpose for syslinux, 
# Do NOT use memtest.bin, use memtest instead of memtest.bin
label memtest (32 bits)
  # MENU DEFAULT
  # MENU HIDE
  MENU LABEL Memory test using Memtest86+ (32 bits)
  # MENU PASSWD
  kernel $sys_files_dir/mt86+x32.mbr
  TEXT HELP
  Run memory test using 32-bit Memtest86+
  ENDTEXT

BOOT_MENU_END
fi

if [ -e "$tmp_sys_files_path/mt86+x64.mbr" ]; then
  cat <<-BOOT_MENU_END >> $output_file

# Note! *.bin is specially purpose for syslinux, 
# Do NOT use memtest.bin, use memtest instead of memtest.bin
label memtest (64 bits)
  # MENU DEFAULT
  # MENU HIDE
  MENU LABEL Memory test using Memtest86+ (64 bits)
  # MENU PASSWD
  kernel $sys_files_dir/mt86+x64.mbr
  TEXT HELP
  Run memory test using 64-bit Memtest86+
  ENDTEXT

BOOT_MENU_END
fi

# The following depends on the image exists or not 
if [ -e "$tmp_sys_files_path/freedos.img" ]; then
  cat <<-BOOT_MENU_END >> $output_file
label FreeDOS
  # MENU DEFAULT
  # MENU HIDE
  MENU LABEL FreeDOS
  # MENU PASSWD
  kernel memdisk
  append initrd=$sys_files_dir/freedos.img
  TEXT HELP
  Run FreeDOS
  ENDTEXT

BOOT_MENU_END
fi
# End of the group "memtest and freedos"
if [ -n "$(ls -l $tmp_sys_files_path/mt86+x*.mbr 2>/dev/null)" ] && \
   [ -e "$tmp_sys_files_path/freedos.img" ]; then
  echo "MENU END" >> $output_file
fi

#
if [ -e "$tmp_sys_files_path/eb.zli" ]; then
  cat <<-BOOT_MENU_END >> $output_file
MENU BEGIN Network Boot

label etherboot
  # MENU DEFAULT
  # MENU HIDE
  MENU LABEL Network boot via etherboot
  # MENU PASSWD
  kernel $sys_files_dir/eb.zli
  TEXT HELP
  Run Etherbot to enable network (PXE) boot
  ENDTEXT

BOOT_MENU_END
fi
if [ -e "$tmp_sys_files_path/gpxe.lkn" ]; then
  cat <<-BOOT_MENU_END >> $output_file
label gPXE
  # MENU DEFAULT
  # MENU HIDE
  MENU LABEL Network boot via gPXE
  # MENU PASSWD
  kernel $sys_files_dir/gpxe.lkn
  TEXT HELP
  Run gPXE to enable network (PXE) boot
  ENDTEXT

MENU END
BOOT_MENU_END
fi
if [ -e "$tmp_sys_files_path/ipxe.lkn" ]; then
  cat <<-BOOT_MENU_END >> $output_file
label iPXE
  # MENU DEFAULT
  # MENU HIDE
  MENU LABEL Network boot via iPXE
  # MENU PASSWD
  kernel $sys_files_dir/ipxe.lkn
  TEXT HELP
  Run iPXE to enable network (PXE) boot
  ENDTEXT

MENU END
BOOT_MENU_END
fi
} # end of gen_config_syslinux
#
gen_config_grub_2_efi(){
local grub_conf="$1"
local bg_img output_file
[ -z "$grub_conf" ] && grub_conf=grub.cfg
bg_img="$(basename $bgimg_file)"
output_file="$output_dir/$grub_conf"
# the timeout is in unit 1/10 sec, convert to sec for grub
timeout_sec="$(echo "scale=0; $timeout /10" | bc -l)"
echo "Adding grub2 efi menus for $output_title..."
cat <<-BOOT_MENU_END > $output_file
#
set pref=/boot/grub
set default="0"
set timeout="$timeout_sec"
# For grub 2.04, a workaround to avoid boot failure is to add "rmmod tpm": https://bugs.debian.org/975835. However, it might fail in secure boot uEFI machine, and the error is like:
# error: verification requested but nobody cares: /live/vmlinuz.
# Out of range pointer 0x3000000004040
# Aborted. Press any key to exit. 
# rmmod tpm

# To set authentication, check
# https://www.gnu.org/software/grub/manual/grub/grub.html#Authentication-and-authorisation
# ‘password’ sets the password in plain text, requiring grub.cfg to be secure; ‘password_pbkdf2’ sets the password hashed using the Password-Based Key Derivation Function (RFC 2898), requiring the use of grub-mkpasswd-pbkdf2 (see Invoking grub-mkpasswd-pbkdf2) to generate password hashes.
# Example:
# set superusers="root"
# password_pbkdf2 root grub.pbkdf2.sha512.10000.biglongstring
# password user1 insecure
# 
# menuentry "May be run by any user" --unrestricted {
# 	set root=(hd0,1)
# 	linux /vmlinuz
# }
# 
# menuentry "Superusers only" --users "" {
# 	set root=(hd0,1)
# 	linux /vmlinuz single
# }
# 
# menuentry "May be run by user1 or a superuser" --users user1 {
# 	set root=(hd0,2)
# 	chainloader +1
# }

# Load graphics (only correspoonding ones will be found)
# (U)EFI
insmod efi_gop
insmod efi_uga
# legacy BIOS
# insmod vbe

if loadfont \$pref/unicode.pf2; then
  set gfxmode=auto
  insmod gfxterm
  # Set the language for boot menu prompt, e.g., en_US, zh_TW...
  set lang=en_US
  terminal_output gfxterm
fi
set hidden_timeout_quiet=false

insmod png
if background_image \$pref/$bg_img; then
  set color_normal=black/black
  set color_highlight=magenta/black
else
  set color_normal=cyan/blue
  set color_highlight=white/blue
fi

# Uncomment the following for serial console
# The command serial initializes the serial unit 0 with the speed 38400bps.
# The serial unit 0 is usually called ‘COM1’. If COM2, use ‘--unit=1’ instead.
#serial --unit=0 --speed=38400
#terminal_input serial
#terminal_output serial

# Decide if the commands: linux/initrd (default) or linuxefi/initrdefi
set linux_cmd=linux
set initrd_cmd=initrd
export linux_cmd initrd_cmd
# Since "linux/initrd" works for uEFI boot, no matter it's secure boot or not. Just use them.
# if [ "\${grub_platform}" = "efi" -a -e "/amd64-release.txt" ]; then
#   # Only amd64 release we switch to linuxefi/initrdefi since it works better with security boot (shim)
#   set linux_cmd=linuxefi
#   set initrd_cmd=initrdefi
# fi

BOOT_MENU_END

if [ "$enable_speech" = "yes" ]; then
cat <<-BOOT_MENU_END >> $output_file
insmod play
play 960 440 1 0 4 440 1

BOOT_MENU_END
fi

cat <<-BOOT_MENU_END >> $output_file
# Since no network setting in the squashfs image, therefore if ip=, the network is disabled.

menuentry "$output_title ($vga_default_prompt)" --id live-default {
  search --set -f $kernel_file
  \$linux_cmd $kernel_file $boot_param $vga_default_mode ip= net.ifnames=0 $quiet_opt $splash_opt $vga_blacklist_opt
  \$initrd_cmd $initrd_file
}

menuentry --hotkey=r "$output_title ($vga_default_prompt & To RAM)" --id live-toram {
  search --set -f $kernel_file
  \$linux_cmd $kernel_file $boot_param $vga_default_mode $toram_opt ip= net.ifnames=0 $quiet_opt $splash_opt $vga_blacklist_opt
  \$initrd_cmd $initrd_file
}

menuentry --hotkey=l "$output_title (VGA with large font & To RAM)" --id live-vga-large-font-toram {
  search --set -f $kernel_file
  \$linux_cmd $kernel_file $boot_param nomodeset $toram_opt ip= net.ifnames=0 $quiet_opt $splash_opt live_console_font_size=16x32
  \$initrd_cmd $initrd_file
}

BOOT_MENU_END

# speech synthesis
if [ "$enable_speech" = "yes" ]; then
  cat <<-BOOT_MENU_END >> $output_file
menuentry --hotkey=s "$output_title (Speech synthesis)"{
  search --set -f $kernel_file
  \$linux_cmd $kernel_file $boot_param $vga_default_mode ip= net.ifnames=0 $quiet_opt $splash_opt $vga_blacklist_opt speakup.synth=soft ---
  \$initrd_cmd $initrd_file
}
BOOT_MENU_END
fi

# Start the submenu for grub2 boot menu
  cat <<-BOOT_MENU_END >> $output_file
submenu 'Other modes of $output_title' {
BOOT_MENU_END

if [ "$show_vga_mode" = "3" ]; then
  cat <<-BOOT_MENU_END >> $output_file
  menuentry "$output_title ($vga_1024x768_prompt)"{
    search --set -f $kernel_file
    \$linux_cmd $kernel_file $boot_param $vga_mode_1024x768 ip= net.ifnames=0 $quiet_opt $splash_opt $vga_blacklist_opt
    \$initrd_cmd $initrd_file
  }
  
  menuentry "$output_title ($vga_640x480_prompt)"{
    search --set -f $kernel_file
    \$linux_cmd $kernel_file $boot_param $vga_mode_640x480 ip= net.ifnames=0 $quiet_opt $splash_opt $vga_blacklist_opt
    \$initrd_cmd $initrd_file
  }
  
BOOT_MENU_END
fi
  cat <<-BOOT_MENU_END >> $output_file
  menuentry --hotkey=K "$output_title (KMS)"{
    search --set -f $kernel_file
    \$linux_cmd $kernel_file $boot_param_rm_nomodeset $vga_mode_1024x768 ip= net.ifnames=0 $quiet_opt $splash_opt
    \$initrd_cmd $initrd_file
  }

  menuentry --hotkey=R "$output_title (KMS & To RAM)" {
    search --set -f $kernel_file
    \$linux_cmd $kernel_file $boot_param_rm_nomodeset $vga_mode_1024x768 $toram_opt ip= net.ifnames=0 $quiet_opt $splash_opt
    \$initrd_cmd $initrd_file
  }
  
  menuentry "$output_title (KMS with large font & To RAM)" --id live-kms-large-font-toram {
    search --set -f $kernel_file
    \$linux_cmd $kernel_file $boot_param_rm_nomodeset $vga_mode_1024x768 $toram_opt ip= net.ifnames=0 $quiet_opt $splash_opt live_console_font_size=16x32
    \$initrd_cmd $initrd_file
  }

BOOT_MENU_END

if [ -n "$lang_locale" ]; then
  cat <<-BOOT_MENU_END >> $output_file
  menuentry "$output_title ($lang_locale, default settings$vga_default_prompt)"{
    search --set -f $kernel_file
    \$linux_cmd $kernel_file $boot_param $vga_default_mode locale=$lang_locale ip= net.ifnames=0 $quiet_opt $splash_opt $vga_blacklist_opt
    \$initrd_cmd $initrd_file
  }
  
BOOT_MENU_END
if [ "$show_vga_mode" = "3" ]; then
  cat <<-BOOT_MENU_END >> $output_file
  menuentry "$output_title ($lang_locale, default settings$vga_1024x768_prompt)"{
    search --set -f $kernel_file
    \$linux_cmd $kernel_file $boot_param $vga_mode_1024x768 locale=$lang_locale ip= net.ifnames=0 $quiet_opt $splash_opt $vga_blacklist_opt
    \$initrd_cmd $initrd_file
  }
  
  menuentry "$output_title ($lang_locale, default settings$vga_640x480_prompt)"{
    search --set -f $kernel_file
    \$linux_cmd $kernel_file $boot_param $vga_mode_640x480 locale=$lang_locale ip= net.ifnames=0 $quiet_opt $splash_opt $vga_blacklist_opt
    \$initrd_cmd $initrd_file
  }
  
BOOT_MENU_END
fi

  cat <<-BOOT_MENU_END >> $output_file
  menuentry "$output_title ($lang_locale, default settings, KMS)"{
    search --set -f $kernel_file
    \$linux_cmd $kernel_file $boot_param_rm_nomodeset $vga_mode_1024x768 locale=$lang_locale ip= net.ifnames=0 $quiet_opt $splash_opt
    \$initrd_cmd $initrd_file
  }
  
  menuentry "$output_title ($lang_locale. To RAM)"{
    search --set -f $kernel_file
    \$linux_cmd $kernel_file $boot_param $vga_default_mode locale=$lang_locale $toram_opt ip= net.ifnames=0 $quiet_opt $splash_opt $vga_blacklist_opt
    \$initrd_cmd $initrd_file
  }
  
BOOT_MENU_END
fi

  cat <<-BOOT_MENU_END >> $output_file
  menuentry "$output_title Safe graphic settings (vga=normal)"{
    search --set -f $kernel_file
    \$linux_cmd $kernel_file $boot_param ip= net.ifnames=0 nomodeset vga=normal nosplash
    \$initrd_cmd $initrd_file
  }
  
  menuentry "$output_title (Failsafe mode)"{
    search --set -f $kernel_file
    \$linux_cmd $kernel_file $boot_param acpi=off irqpoll noapic noapm nodma nomce nolapic nosmp ip= net.ifnames=0 nomodeset vga=normal nosplash
    \$initrd_cmd $initrd_file
  }
}  

BOOT_MENU_END
# End of the submenu for grub2 boot menu

# localboot
cat <<-GRUB_END >> $output_file
menuentry "Local operating system (if available)" --id local-disk {
  echo "Booting first local disk..."
  # Generate boot menu automatically
  configfile /boot/grub/boot-local-efi.cfg
  # If not chainloaded, definitely no uEFI boot loader was found.
  echo "No uEFI boot loader was found!"
  sleep 15
}

GRUB_END

cat <<-BOOT_MENU_END >> $output_file
menuentry --hotkey=m "Memtester ($vga_default_prompt & To RAM)" --id memtester {
  search --set -f $kernel_file
  \$linux_cmd $kernel_file $boot_param $vga_default_mode $toram_opt ip= net.ifnames=0 $quiet_opt $splash_opt $vga_blacklist_opt init=/bin/bash -- -c "/sbin/ocs-memtester"
  \$initrd_cmd $initrd_file
}

BOOT_MENU_END

# The following depends on the image exists or not 

# For memtest86+ in uEFI BIOS:
# memtest86+x64.efi -> mt86+x64.efi
if [ -e "$tmp_sys_files_path/mt86+x64.efi" ]; then
  cat <<-BOOT_MENU_END >> $output_file
menuentry "Memtest using Memtest86+" --id memtest86+ {
  search --no-floppy --set=root -f $sys_files_dir/mt86+x64.efi
  linux $sys_files_dir/mt86+x64.efi
}

BOOT_MENU_END
fi

if [ -e "$tmp_sys_files_path/freedos.img" ]; then
  cat <<-BOOT_MENU_END >> $output_file
#menuentry "FreeDOS"{
#  linux16 memdisk
#  initrd $sys_files_dir/freedos.img
#}

BOOT_MENU_END
fi
if [ -e "$tmp_sys_files_path/eb.zli" ]; then
  cat <<-BOOT_MENU_END >> $output_file
#menuentry "etherboot"{
#  search --set -f $sys_files_dir/eb.zli
#  linux16 $sys_files_dir/eb.zli
#}

BOOT_MENU_END
fi
if [ -e "$tmp_sys_files_path/gpxe.lkn" ]; then
  cat <<-BOOT_MENU_END >> $output_file
#menuentry "gPXE" {
#  search --set -f $sys_files_dir/gpxe.lkn
#  linux16 $sys_files_dir/gpxe.lkn
#}

BOOT_MENU_END
fi
if [ -e "$tmp_sys_files_path/ipxe.efi" ]; then
  cat <<-BOOT_MENU_END >> $output_file
menuentry "Network boot via iPXE" {
  search --no-floppy --set=root -f $sys_files_dir/ipxe.efi
  chainloader $sys_files_dir/ipxe.efi + 1
}

BOOT_MENU_END
fi

#
cat <<-BOOT_MENU_END >> $output_file
menuentry 'uEFI firmware setup' 'uefi-firmware' {
  echo "Entering uEFI firmware setup..."
  fwsetup
}

menuentry "$output_title $version_no info"{
  echo $boot_menu_txt_say_pkg
  echo $boot_menu_txt_say_org
  echo $project_url
  echo \\${extraprompt}
  echo \\${boot_menu_pkg_ver_cpright}
  echo \\${boot_menu_pkg_disclaimer}
  sleep --verbose --interruptible 10
}

BOOT_MENU_END
} # end of gen_config_grub_2_efi

################
##### MAIN #####
################
# Default settings
show_vga_mode="3"
fb_mode="vesafb"
# Option for disabling VGA blacklist
# Ref: http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=686939
vga_blacklist_list="i915.blacklist=yes radeonhd.blacklist=yes nouveau.blacklist=yes vmwgfx.enable_fbdev=1"
# Initial value to be put in the boot parameters
vga_blacklist_opt=""
# Parse command-line options
while [ $# -gt 0 ]; do
  case "$1" in
    -l|--language)
            shift
            if [ -z "$(echo $1 |grep ^-.)" ]; then
              # skip the -xx option, in case 
              specified_lang="$1"
              shift
            fi
	    [ -z "$specified_lang" ] && USAGE && exit 1
            ;;
    -b|--bg-mode)
            shift
            if [ -z "$(echo $1 |grep ^-.)" ]; then
              # skip the -xx option, in case 
              bg_mode="$1"
              shift
            fi
	    [ -z "$bg_mode" ] && USAGE && exit 1
            ;;
    -c|--toram-mode)
            shift
            if [ -z "$(echo $1 |grep ^-.)" ]; then
              # skip the -xx option, in case 
              toram_mode="$1"
              shift
            fi
	    [ -z "$toram_mode" ] && USAGE && exit 1
            ;;
    -d|--dark-bg)
            shift
            background_mode="dark"
            ;;
    -f|--framebuffer-mode)
            shift
            if [ -z "$(echo $1 |grep ^-.)" ]; then
              # skip the -xx option, in case 
              vga_mode="$1"
              shift
            fi
	    [ -z "$vga_mode" ] && USAGE && exit 1
            ;;
    -t|--timeout)
            shift
            if [ -z "$(echo $1 |grep ^-.)" ]; then
              # skip the -xx option, in case 
              timeout="$1"
              shift
            fi
	    [ -z "$timeout" ] && USAGE && exit 1
            ;;
    -g1|grub-hd-dev)
            shift
            if [ -z "$(echo $1 |grep ^-.)" ]; then
              # skip the -xx option, in case 
              op_hd_dev_grub="$1"
              shift
            fi
	    [ -z "$op_hd_dev_grub" ] && USAGE && exit 1
            ;;
    -g2|grub-part-no)
            shift
            if [ -z "$(echo $1 |grep ^-.)" ]; then
              # skip the -xx option, in case 
              op_part_no_grub="$1"
              shift
            fi
	    [ -z "$op_part_no_grub" ] && USAGE && exit 1
            ;;
    -g3|OS-root-dev)
            shift
            if [ -z "$(echo $1 |grep ^-.)" ]; then
              # skip the -xx option, in case 
              output_dev_grub="$1"
              shift
            fi
	    [ -z "$output_dev_grub" ] && USAGE && exit 1
            ;;
    -k|--kernel-file)
            shift
            if [ -z "$(echo $1 |grep ^-.)" ]; then
              # skip the -xx option, in case 
              kernel_file="$1"
              shift
            fi
	    [ -z "$kernel_file" ] && USAGE && exit 1
            ;;
    -i|--initrd-file)
            shift
            if [ -z "$(echo $1 |grep ^-.)" ]; then
              # skip the -xx option, in case 
              initrd_file="$1"
              shift
            fi
	    [ -z "$initrd_file" ] && USAGE && exit 1
            ;;
    -n|--version-no)
            shift
            if [ -z "$(echo $1 |grep ^-.)" ]; then
              # skip the -xx option, in case 
              version_no="$1"
              shift
            fi
	    [ -z "$version_no" ] && USAGE && exit 1
            ;;
    -p|--boot-param)
            shift
            if [ -z "$(echo $1 |grep ^-.)" ]; then
              # skip the -xx option, in case 
              boot_param="$1"
              shift
            fi
	    [ -z "$boot_param" ] && USAGE && exit 1
            ;;
    -e|--title)
            shift
            if [ -z "$(echo $1 |grep ^-.)" ]; then
              # skip the -xx option, in case 
              output_title="$1"
              shift
            fi
	    [ -z "$output_title" ] && USAGE && exit 1
            ;;
    -m|--bgimg)
            shift
            if [ -z "$(echo $1 |grep ^-.)" ]; then
              # skip the -xx option, in case 
              bgimg_file="$1"
              shift
            fi
	    [ -z "$bgimg_file" ] && USAGE && exit 1
            ;;
    -r|--extraprompt)
            shift
            if [ -z "$(echo $1 |grep ^-.)" ]; then
              # skip the -xx option, in case 
              extraprompt="$1"
              shift
            fi
	    [ -z "$extraprompt" ] && USAGE && exit 1
            ;;
    -j|--enable-speech)
            shift
            enable_speech="yes"
            ;;
    -s|--show-only-one-vga)
            shift
            show_vga_mode="1"
            ;;
    -sp|--splash)
            shift
            splash_opt="splash"
            ;;
    -u|--use-uvesafb)
            shift
            fb_mode="uvesafb"
            ;;
    -q|--quiet)
            shift
            quiet_opt="quiet"
            ;;
    -a|--splash)
            shift
            splash_opt="splash"
            ;;
    -vb|--vga-blacklist)
            shift
            vga_blacklist_opt="$vga_blacklist_list"
            ;;
    -z|--add-lang-menu)
            shift
            if [ -z "$(echo $1 |grep ^-.)" ]; then
              # skip the -xx option, in case 
              lang_locale="$1"
              shift
            fi
	    [ -z "$lang_locale" ] && USAGE && exit 1
            ;;
    -*)     echo "${0}: ${1}: invalid option" >&2
            USAGE >& 2
            exit 2 ;;
    *)      break ;;
  esac
done

output_format="$1"
output_dir="$2"
[ -z "$output_format" ] && USAGE && exit 1
[ -z "$output_dir" ] && USAGE && exit 1
[ -z "$vga_mode" ] && vga_mode=$VGA_MODE_DEF
[ -z "$timeout" ] && timeout=$TIMEOUT_DEF
[ -z "$kernel_file" ] && kernel_file="$KERNEL_FILE_DEFAULT"
[ -z "$initrd_file" ] && initrd_file="$INITRD_FILE_DEFAULT"
[ -z "$boot_param" ] && boot_param="$BOOT_PARAM_DEFAULT"
[ -z "$op_hd_dev_grub" ] && op_hd_dev_grub="$OP_HD_DEV_GRUB_DEF"
[ -z "$op_part_no_grub" ] && op_part_no_grub="$OP_PART_NO_GRUB_DEF"
[ -z "$output_dev_grub" ] &&  output_dev_grub="$OUTPUT_DEV_GRUB_DEF"
[ -z "$output_title" ] && output_title="$OUTPUT_TITLE_DEF"
[ -z "$bgimg_file" ] && bgimg_file="$BGIMG_FILE_DEF"
[ -z "$version_no" ] && version_no="Unknown/customized"
[ -z "$toram_mode" ] && toram_mode="$TORAM_MODE_DEF"
if [ "$enable_speech" = "yes" ]; then
  beep_ascii=""
fi

# 2016/03/30 Use $boot_param directly instead of $boot_param_toram_extra
# 2014/01/10 No need to add "noeject" here. "toram" for live-boot will handle that.
# Thanks to Ady <ady-sf _at_ hotmail com> for the bug report.
## boot_param_toram_extra is specially for "To RAM" menu. We will append noeject if it does not containt that.
#if [ -z "$(echo $boot_param | grep -Ew "noeject")" ]; then
#  boot_param_toram_extra="$boot_param noeject"
#else
#  boot_param_toram_extra="$boot_param"
#fi
#boot_param_toram_extra="$boot_param"

# For KMS, we need to remove "nomodeset" if it exists in $boot_param
boot_param_rm_nomodeset="$(echo $boot_param | sed -r -e "s/[[:space:]]*nomodeset[[:space:]]*/ /g")"

#
now_year="$(LC_ALL=C date +%Y)"
if [ -n "$(echo $output_title | grep -i clonezilla)" ]; then
  boot_menu_txt_say_pkg="Clonezilla, the OpenSource Clone System."
  boot_menu_txt_say_org="NCHC Free Software Labs, Taiwan."
  project_url="clonezilla.org, clonezilla.nchc.org.tw"
  boot_menu_pkg_ver_cpright="* Clonezilla live version: $version_no. (C) 2003-${now_year}, NCHC, Taiwan"
  boot_menu_pkg_disclaimer="* Disclaimer: Clonezilla comes with ABSOLUTELY NO WARRANTY"
elif [ -n "$(echo $output_title | grep -i drbl)" ]; then
  boot_menu_txt_say_pkg="DRBL (Diskless Remote Boot in Linux)."
  boot_menu_txt_say_org="NCHC Free Software Labs, Taiwan."
  project_url="drbl.sourceforge.net, drbl.nchc.org.tw"
  boot_menu_pkg_ver_cpright="* DRBL live version: $version_no. (C) 2003-${now_year}, NCHC, Taiwan"
  boot_menu_pkg_disclaimer="* Disclaimer: DRBL comes with ABSOLUTELY NO WARRANTY"
elif [ -n "$(echo $output_title | grep -i gparted)" ]; then
  boot_menu_txt_say_pkg="GParted."
  boot_menu_txt_say_org="Gnome Partition Editor."
  project_url="https://gparted.org"
  boot_menu_pkg_ver_cpright="* GParted live version: $version_no. Live version maintainer: $GPARTED_LIVE_MAINTAINER"
  boot_menu_pkg_disclaimer="* Disclaimer: GParted live comes with ABSOLUTELY NO WARRANTY"
else
  project_url="Welcome!"
fi
#
# Now we put other boot image files, like etherboot, fdos and memtest in the same dir with kernel and initrd. Therefore using $sys_files_dir (Ex: /casper, /live). This is used for the config file of boot manager (grub, syslinux).
sys_files_dir="$(dirname $kernel_file)"
# This is the absolute path for the output dir.
# $output_dir could be 1 layer of sub dir under tmp dir (e.g. $tmpdir/isolinux) or 2 layers of sub dirs (e.g. $tmpdir/EFI/boot)
if [ -d "$output_dir/../$sys_files_dir" ]; then
  tmp_sys_files_path="$output_dir/../$sys_files_dir"
elif [ -d "$output_dir/../../$sys_files_dir" ]; then
  tmp_sys_files_path="$output_dir/../../$sys_files_dir"
fi
ask_and_load_lang_set $specified_lang

#
case "$bg_mode" in 
   txt|TXT|text|TEXT)
      MENUC32="menu.c32"
      mask="#"
      ;;
   *)
      MENUC32="vesamenu.c32" ;;
esac

#
case "$fb_mode" in
  vesafb) 
           vga_mode_640x480="vga=785"
           vga_mode_800x600="vga=788" 
           vga_mode_1024x768="vga=791"
	   ;;
  uvesafb) 
           vga_mode_640x480="video=uvesafb:mode_option=640x480-16"
           vga_mode_800x600="video=uvesafb:mode_option=800x600-16" 
           vga_mode_1024x768="video=uvesafb:mode_option=1024x768-32"
	   ;;
esac
#
case "$show_vga_mode" in
  1) # For 1 mode, we respect the $vga_mode, and we do not show the resolution. Since if we show it in the distribution (e.g. DRBL live), user will be confused.
     vga_640x480_prompt=""
     vga_800x600_prompt=""
     vga_1024x768_prompt=""
     vga_default_prompt="Default settings"
     case "$vga_mode" in
      785) vga_default_mode="$vga_mode_640x480";;
      788) vga_default_mode="$vga_mode_800x600";;
      791) vga_default_mode="$vga_mode_1024x768";;
      *) vga_default_mode="";
     esac
     ;;
  *) # For 3 modes, we force to set default as 800x600.
     vga_640x480_prompt="VGA 640x480"
     vga_800x600_prompt="VGA 800x600" 
     vga_1024x768_prompt="VGA 1024x768"
     vga_default_prompt="VGA 800x600"
     vga_default_mode="$vga_mode_800x600"
     ;;
esac

# Prepare required files
cp $drbl_syscfg/boot-local-efi.cfg $output_dir/

#
case "$toram_mode" in
  compact) toram_opt="toram=filesystem.squashfs";;
  live)    toram_opt="toram=live,syslinux,EFI,boot,.disk,utils";;
  all)     toram_opt="toram";;
esac

#
case "$output_format" in 
   isolinux|ISOLINUX)
      gen_config_syslinux isolinux ;;
   syslinux|SYSLINUX)
      gen_config_syslinux syslinux ;;
   grub-efi|GRUB-EFI|grub2-efi|GRUB2-EFI|grub2-efi-ia32|GRUB2-EFI-IA32|grub2-efi-x64|GRUB2-EFI-X64)
      # For grub2, no matter it's ia32 or x86-64, the config file is grub.cfg.
      gen_config_grub_2_efi grub.cfg ;;
   *)
      [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
      echo "Unknown mode for output format!"
      [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
      echo "$msg_program_stop!"
      my_ocs_exit 1
esac
