#!/bin/ash

error_exit() {
	if [ "$1" ]; then
		$YAD_EXE $YAD_STD_OPTS --title "FrugalPup-isoboot v${VER}" --width=220 --text-align=center \
			--text "${1}" \
			--button=gtk-ok:0
	fi
	[ -d "$ISO_FILES" ] && rm -rf "$ISO_FILES"
	exit 1
}

EXE_DIR="$(dirname $(readlink -f ${0}))"
COMN_FN="$EXE_DIR/frugalpup-common"
[ -f "$COMN_FN" ] && . "$COMN_FN"

G2_TAR=''
[ -f "$EXE_DIR/grub2.tar.xz" ] && G2_TAR="$EXE_DIR/grub2.tar.xz"
[ "$G2_TAR" ] || error_exit "File <span foreground='purple'>$EXE_DIR/grub2.tar.xz</span> not found."

INSTALL_DIR="$($YAD_EXE $YAD_STD_OPTS --title "FrugalPup-isoboot v${VER} - Select install directory." \
	--file --directory --width=600 --height=460 \
	--text " Select the directory containing Puppy frugal install(s)." \
	--filename="/mnt/" \
	--button="Quit!${EXIT_ICON}:1" --button=gtk-ok:0)"
[ $? -eq 0 ] || error_exit

ISO_FILES='/tmp/iso_root'

[ -d "$ISO_FILES" ] && rm -rf "$ISO_FILES"
mkdir -p "$ISO_FILES"
tar xf "$G2_TAR" -C "$ISO_FILES" >/dev/null

"$EXE_DIR/frugalpup-bootentry" "$INSTALL_DIR" uefi "$ISO_FILES"

cat >> "$ISO_FILES/grub.cfg" << GRUB
menuentry "Shutdown computer" {
	halt
}
menuentry "Reboot computer" {
	reboot
}
GRUB

ISO_FN="$HOME/puppy_boot.iso"

$YAD_EXE $YAD_STD_OPTS --title "FrugalPup-isoboot v${VER} - confirm" --width=260 \
	--text "The generated contents are now present in <span foreground='purple'>$ISO_FILES</span>

The grub2 configuration file <span foreground='purple'>$ISO_FILES/grub.cfg</span> can be edited before writing the iso file <span foreground='purple'>$ISO_FN</span>

Click <span foreground='blue'>OK</span> when ready to continue." \
	--button="Quit!${EXIT_ICON}:1" --button=gtk-ok:0
	[ $? -eq 0 ] || error_exit

[ -f "$ISO_FN" ] && rm "$ISO_FN"
mkisofs -R -b boot/grub/i386-pc/eltorito.img -no-emul-boot -boot-info-table -boot-load-size 4 -o "$ISO_FN" "$ISO_FILES" 2>/dev/null

[ -d "$ISO_FILES" ] && rm -rf "$ISO_FILES"

exit
