#!/bin/ash

do_exit() {
	[ -f "$TMP_LIST" ] && rm "$TMP_LIST"
	[ -f "$TMP_BLK" ] && rm "$TMP_BLK"
	while IFS='' read ONE_MP; do
		umount "$ONE_MP" 2>/dev/null
	done < "$MNTD_FN"
	rm -f "$MNTD_FN"
	if [ "$1" ]; then
		yad $YAD_STD_OPTS --title "FrugalPup-bootfiles v${VER}" --width=220 --text-align=center \
			--text "${1}" \
			--button=gtk-ok:0
	fi
	"$EXE_DIR/frugalpup" &
	exit $2
}

error_exit() {
	do_exit "$1" 1
}

normal_exit() {
	do_exit "$1" 0
}

#set -x ; exec &> /tmp/frugalpup-bootfiles.log

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"

MNTD_FN="/tmp/frugalpup_$$_did_mount.txt"
[ -f "$MNTD_FN" ] && rm -f "$MNTD_FN"

TMP_BLK="/tmp/${0##*/}_$$_blk_list.txt"
TMP_LIST="/tmp/${0##*/}_$$_tmp_list.txt"

busybox blkid | grep -v 'squashfs' | grep -v 'swap' | grep -v 'zram' | sort > "$TMP_BLK"
[ "$(grep 'vfat' "$TMP_BLK")" ] || error_exit "No fat32 partitions found."

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

[ -f "$TMP_LIST" ] && rm "$TMP_LIST"
while read ONE_LINE; do
	TYPE="${ONE_LINE#*TYPE=\"}"
	[ "${TYPE:0:1}" = "/" ] && TYPE='' || TYPE="${TYPE%%\"*}"
	case $TYPE in
		crypto_LUKS|iso9660|udf) continue ;;
		*) ;;
	esac
	DRV="${ONE_LINE%%:*}"; DRV="${DRV#/dev/}"
	LAB="${ONE_LINE#*LABEL=\"}"
	[ "${LAB:0:1}" = "/" ] && LAB='' || LAB="${LAB%%\"*}"
	[ "$LAB" = "System Reserved" ] && continue
	[ "$LAB" = "" -a "$TYPE" = "ntfs" ] && continue
	UUID="${ONE_LINE#*UUID=\"}"
	[ "${UUID:0:1}" = "/" ] && UUID='' || UUID="${UUID%%\"*}"
	echo "$DRV" >> "$TMP_LIST"
	echo "$TYPE" >> "$TMP_LIST"
	echo "$LAB" >> "$TMP_LIST"
	echo "$UUID" >> "$TMP_LIST"
done < "$TMP_BLK"

if [ -s "$TMP_LIST" ]; then
	if [ "$SFS_PART" ]; then
		TMSG="<span foreground='purple'>$SFS_PART</span> is the default partition containing Puppy install(s).
Simply click <span foreground='blue'>OK</span> to use it,
Or,
select a partition containing Puppy frugal install(s):"
		THT=240
	else
		TMSG="Select the partition containing Puppy frugal install(s):"
		THT=200
	fi
	SRC_SPEC="$(yad $YAD_STD_OPTS --title "FrugalPup-bootfiles v${VER} - Puppy partition" --width=270 --height=$THT \
		--text "$TMSG" \
		--list --column=Part --column=Type --column=Label --column=UUID:HD < $TMP_LIST)"
	[ $? -eq 0 ] || error_exit
	rm "$TMP_LIST"
	if [ "$SRC_SPEC" ]; then
		SRC_PART="${SRC_SPEC%%|*}"
	elif [ "$SFS_PART" ]; then
		SRC_PART="$SFS_PART"
	else
		error_exit "No partition selected."
	fi
else
	error_exit "No suitable Puppy partitions found."
fi

ensure_mounted "$SRC_PART"
[ "$ensure_mounted_DID" ] && echo "$ensure_mounted_MP" >> "$MNTD_FN"
[ "$ensure_mounted_MP" ] || error_exit "Could not mount \"$SRC_PART\"."
SRC_MP="$ensure_mounted_MP"

SRC_DIR="$(yad $YAD_STD_OPTS --title "FrugalPup-bootfiles v${VER} - Puppy directory." \
	--file --directory --width=600 --height=560 \
	--text " Select the directory containing Puppy frugal install(s).

 Assuming your Puppy frugal installs are stored in sub-directories like:
       <span foreground='purple'>$SRC_MP/puppy/slacko</span>
       <span foreground='purple'>$SRC_MP/puppy/upupbb</span>
 if you select the parent directory:
       <span foreground='purple'>$SRC_MP/puppy</span>
       Then all the Puppy installs in sub-directories will be processed.
 if you select a Puppy install directory:
       <span foreground='purple'>$SRC_MP/puppy/slacko</span>
       Then only the <span foreground='purple'>slacko</span> install will be processed.
" \
	--filename="$SRC_MP${SFS_DIR%/*}/")"
[ $? -eq 0 ] || error_exit

DIR_MP="$(stat -Lc %m "$SRC_DIR")"
if [ "$DIR_MP" != "$SRC_MP" ]; then
	SRC_PART="$(grep -m1 "$DIR_MP" /proc/mounts | cut -f1 -d' ')"
	SRC_PART="${SRC_PART#/dev/}"
	SRC_MP="$DIR_MP"
fi

PUPS="$(find "$SRC_DIR" -maxdepth 2 -type f -name 'puppy_*.sfs')"
[ "$PUPS" ] || error_exit "No Puppy frugal installs found in \"$SRC_DIR\"."

[ -f "$TMP_LIST" ] && rm "$TMP_LIST"
grep 'vfat' "$TMP_BLK" |
while IFS='' read ONE_LINE; do
	DRV="${ONE_LINE%%:*}"; DRV="${DRV#/dev/}"
	DRV_ONE="${DRV%[0-9]}"; DRV_ONE="${DRV_ONE%[0-9]}"; DRV_ONE="${DRV_ONE%[0-9]}"
	DRV_ONE="${DRV_ONE}1"
	[ "$DRV" = "$DRV_ONE" ] || continue
	LAB="${ONE_LINE#*LABEL=\"}"
	[ "${LAB:0:1}" = "/" ] && LAB='' || LAB="${LAB%%\"*}"
	echo "$DRV" >> "$TMP_LIST"
	echo "$LAB" >> "$TMP_LIST"
done

if [ -s "$TMP_LIST" ]; then
	DEST_SPEC="$(yad $YAD_STD_OPTS --title "FrugalPup-bootfiles v${VER} - Boot partition" \
		--text "This script updates the selected boot partition,
with files needed to boot the Puppy frugal install(s) in,
<span foreground='purple'>$SRC_DIR</span>.

<span foreground='red'>Will overwrite boot files on the selected partition.</span>

Select a fat32 boot partition:" \
		--list --print-column=1 --column=Partition --column=Label < $TMP_LIST)"
	[ $? -eq 0 ] || error_exit
	rm "$TMP_LIST"
	[ "$DEST_SPEC" ] || error_exit "No partition selected."
	DEST_PART="${DEST_SPEC%%|*}"
else
	error_exit "No suitable fat32 partitions found.
They must be the first partition on the disk."
fi

ensure_mounted "$DEST_PART"
[ "$ensure_mounted_DID" ] && echo "$ensure_mounted_MP" >> "$MNTD_FN"
[ "$ensure_mounted_MP" ] || error_exit "Could not mount \"$DEST_PART\"."
DEST_MP="$ensure_mounted_MP"
if [ -d "$DEST_MP/EFI/Microsoft" ]; then
	HAVE_WIN_BOOT='yes'
else
	HAVE_WIN_BOOT=''
fi
if [ "$HAVE_WIN_BOOT" ]; then
	yad $YAD_STD_OPTS --title "DiskPup v${VER}" --width=500 \
		--text "<big>The <span foreground='purple'>$DEST_PART</span> partition already contains a Windows UEFI boot.
Continuing with this install could damage this boot facility.

It is recommended that you click <span foreground='blue'>Cancel</span>, to abort this install.
Then choose a different fat32 partition. A usb stick would do.</big>"
	[ $? -eq 0 ] || error_exit
fi

CAN_MBR=''
if [ -f "$MBR_TAR" ]; then
	get_device "$DEST_PART"
	if [ "$get_device_RET" ]; then
		[ "$(parted "/dev/$get_device_RET" print 2>/dev/null | grep 'msdos')" ] && CAN_MBR='yes'
	fi
fi

if [ "$CAN_MBR" ]; then
	BOOT_SPEC="$(yad $YAD_STD_OPTS --title "FrugalPup-bootfiles v${VER} - Boot type" \
		--text "Select the boot type:" \
		--list --no-headers --print-column=3 --radiolist --column=:RD --column=:TXT --column=:TXT \
		FALSE '    ' 'uefi' FALSE '    ' 'mbr' TRUE '    ' 'both')"
	[ $? -eq 0 ] || error_exit
	BOOT_TYPE="${BOOT_SPEC%%|*}"
else
	BOOT_TYPE='uefi'
fi

DO_UEFI=''; DO_MBR=''
case "$BOOT_TYPE" in
	uefi)
		DSP_BOOT='uefi'
		DO_UEFI='yes'
		;;
	mbr)
		DSP_BOOT='mbr'
		DO_MBR='yes'
		;;
	both)
		DSP_BOOT="uefi</span> and <span foreground='purple'>mbr"
		DO_UEFI='yes'
		DO_MBR='yes'
		;;
esac

get_part_id "$DEST_PART"
DEST_ID="$get_part_id_RET"
get_part_id "$SRC_PART"
SRC_ID="$get_part_id_RET"

SRC_DIR_REL="${SRC_DIR#${SRC_MP}}"
SRC_DIR_DISP="$SRC_DIR_REL"
[ "$SRC_DIR_DISP" ] || SRC_DIR_DISP='/'
yad $YAD_STD_OPTS --title "FrugalPup-bootfiles v${VER} - confirm" --width=260 \
	--text "About to write boot files to:
    Partition: <span foreground='purple'>$DEST_PART</span> [<span foreground='purple'>$DEST_ID</span>]
    Directory: <span foreground='purple'>/</span>

Boot type: <span foreground='purple'>$DSP_BOOT</span>

Source for Puppy files:
    Partition: <span foreground='purple'>$SRC_PART</span> [<span foreground='purple'>$SRC_ID</span>]
    Directory: <span foreground='purple'>$SRC_DIR_DISP</span>

Click <span foreground='blue'>OK</span> to continue."
[ $? -eq 0 ] || error_exit

echo "SFS_PART='$SRC_PART'" > "$CACHE_FN"
echo "SFS_DIR='$SRC_DIR_REL'" >> "$CACHE_FN"
echo "DEST_PART='$DEST_PART'" >> "$CACHE_FN"
echo "BOOT_TYPE='$BOOT_TYPE'" >> "$CACHE_FN"
ERR_MSG="$("$EXE_DIR/frugalpup-dobootpart")"
[ $? -eq 0 ] || error_exit "frugalpup-dobootpart: $ERR_MSG"

normal_exit "Grub2 boot files written to partition <span foreground='purple'>$DEST_PART</span>."
