#!/bin/ash

do_exit() {
	[ "$SRC_MTD" ] && umount "$SRC_MP" 2>/dev/null
	[ "$DEST_MTD" ] && umount "$DEST_MP" 2>/dev/null
	[ "$XPID" ] && kill -9 $XPID 2>/dev/null
	[ "$1" ] && echo "${1}"
	exit $2
}

error_exit() {
	do_exit "$1" 1
}

normal_exit() {
	do_exit "$1" 0
}

#set -x ; exec &> /tmp/do-boot-part.log

XPID=''

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

[ -f "$UTILS_DIR/functions_part" ] || error_exit "File <span foreground='purple'>$UTILS_DIR/functions_part</span> not found."
. "$UTILS_DIR/functions_part"

EFI_TAR="$(find $EXE_DIR -name '*-efi.tar.xz' | head -n1)"
[ "$EFI_TAR" ] || error_exit "grub2-efi support missing"

MBR_TAR="$(find $EXE_DIR -name '*-mbr.tar.xz' | head -n1)"
[ "$MBR_TAR" ] || error_exit "grub2-mbr support missing"

SFS_PART=''; SFS_DIR=''; DEST_PART=''; BOOT_TYPE=''
[ "$CACHE_FN" ] && [ -f "$CACHE_FN" ] && . "$CACHE_FN"

[ "$SFS_PART" ] || error_exit "No install partition specified"
[ "$DEST_PART" ] || error_exit "No boot partition specified"
[ "$(blkid "/dev/$DEST_PART" | grep 'vfat')" ] || error_exit "\"$DEST_PART\" is not a fat32 partition"

[ "$BOOT_TYPE" ] || BOOT_TYPE='uefi'
DO_UEFI=''; DO_MBR=''
case "$BOOT_TYPE" in
	uefi) DO_UEFI='yes' ;;
	mbr) DO_MBR='yes' ;;
	both) DO_UEFI='yes'; DO_MBR='yes' ;;
esac

gtkdialog-splash -bg yellow -close box -text "Copying boot files to $DEST_PART" &
XPID=$!

ensure_mounted "$SFS_PART"
SRC_MP="$ensure_mounted_MP"
SRC_MTD="$ensure_mounted_DID"
[ "$ensure_mounted_MP" ] || error_exit "Could not mount \"$SFS_PART\"."
SRC_DIR="${SRC_MP}${SFS_DIR}"

ensure_mounted "$DEST_PART"
DEST_MP="$ensure_mounted_MP"
DEST_MTD="$ensure_mounted_DID"
[ "$ensure_mounted_MP" ] || error_exit "Could not mount \"$DEST_PART\"."

if [ "$DO_UEFI" ]; then
#	echo "efi"
	tar -xf "$EFI_TAR" --overwrite -C "$DEST_MP" >/dev/null
	[ $? -eq 0 ] || error_exit "Failed to write Grub2 efi files to \"$DEST_PART\""
fi

if [ "$DO_MBR" ]; then
#	echo "mbr"
	tar -xf "$MBR_TAR" --overwrite -C "$DEST_MP" >/dev/null
	[ $? -eq 0 ] || error_exit "Failed to write Grub2 mbr files to \"$DEST_PART\""
	get_device "$DEST_PART"
	"$EXE_DIR/bootlace.com" --boot-prevmbr-last --time-out=0 /dev/$get_device_RET > /dev/null
	[ $? -eq 0 ] || error_exit "Failed to write grub4dos mbr to \"$get_device_RET\""
fi

cat "$EXE_DIR/cfg-top-${BOOT_TYPE}.txt" > "$DEST_MP/grub.cfg"
ERR_MSG="$("$EXE_DIR/frugalpup-bootentry" "$SRC_DIR" fs "$DEST_MP")"
[ $? -eq 0 ] || error_exit "$ERR_MSG"
cat "$EXE_DIR/cfg-bot.txt" >> "$DEST_MP/grub.cfg"

sync
if [ "$SFS_PART" = "$DEST_PART" ]; then
	DEST_MTD="$SRC_MTD"
else
	[ "$SRC_MTD" ] && umount "$SRC_MP"
	sync
fi
if [ "$DEST_MTD" ]; then
	sleep 1
	umount "$DEST_MP"
	[ $? -eq 0 ] || { sleep 1; umount "$DEST_MP"; }
fi

normal_exit
