#!/bin/ash

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

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

MBR_TAR=''
[ -f "$EXE_DIR/grub2-mbr.tar.xz" ] && MBR_TAR="$EXE_DIR/grub2-mbr.tar.xz"
[ "$MBR_TAR" ] || error_exit "grub2 support missing"

ISO_TAR=''
[ -f "$EXE_DIR/grub2-iso.tar.xz" ] && ISO_TAR="$EXE_DIR/grub2-iso.tar.xz"
[ "$ISO_TAR" ] || error_exit "grub2 support missing"


INSTALL_DIR="$(yad $YAD_STD_OPTS --title "FrugalPup-bootcd v${VER} - Puppy directory." \
	--file --directory --width=600 --height=460 \
	--text " Select the directory containing Puppy frugal install(s)." \
	--filename="/mnt/")"
[ $? -eq 0 ] || error_exit

ISO_FILES='/tmp/iso_root'

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

[ -f "$ISO_FILES/menu.lst" ] && rm "$ISO_FILES/menu.lst"
[ -f "$ISO_FILES/grldr" ] && rm "$ISO_FILES/grldr"
[ -f "$ISO_FILES/boot/grub/i386-pc/core.img" ] && rm "$ISO_FILES/boot/grub/i386-pc/core.img"

cat "$EXE_DIR/cfg-top-mbr.txt" > "$ISO_FILES/grub.cfg"
ERR_MSG="$("$EXE_DIR/frugalpup-bootentry" "$INSTALL_DIR" fs "$ISO_FILES")"
[ $? -eq 0 ] || error_exit "$ERR_MSG"
cat "$EXE_DIR/cfg-bot.txt" >> "$ISO_FILES/grub.cfg"

ISO_FN="$HOME/puppy_boot.iso"
#ISO_FN="./puppy_boot.iso"

yad $YAD_STD_OPTS --title "FrugalPup-bootcd 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."
	[ $? -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"

"$EXE_DIR/frugalpup" &

exit
