#!/bin/ash

do_exit() {
	[ "$STICK_LIST" ] && [ -f "$STICK_LIST" ] && rm "$STICK_LIST"
	[ "$TMP_BLK" ] && [ -f "$TMP_BLK" ] && rm "$TMP_BLK"
	[ "$CACHE_FN" ] && [ -f "$CACHE_FN" ] && rm "$CACHE_FN"
	[ "$TMP_SRC_DIR" ] && [ -d "$TMP_SRC_DIR" ] && rm -rf "$TMP_SRC_DIR"
	[ "$SRC_MTD" ] && umount "$SRC_MTD" 2>/dev/null
	[ "$XPID" ] && kill -9 $XPID 2>/dev/null
	if [ "$1" ]; then
		yad $YAD_STD_OPTS --title "StickPup v${VER}" --width=220 --text-align=center \
			--text "<big>${1}</big>" \
			--button=gtk-ok:0
	fi
	exit $2
}

error_exit() {
	do_exit "$1" 1
}

normal_exit() {
	do_exit "$1" 0
}

# check Grub2 uefi and mbr
grub2_chk() {
	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"
}

boot_part_chk() {
	STICK_LIST="/tmp/${0##*/}_vfat_list.txt"
	[ -f "$STICK_LIST" ] && rm "$STICK_LIST"

	get_device "$SRC_PART"

	SEL='TRUE'
	probedisk | grep 'usb' |
	while IFS='' read ONE_LINE; do
		DRV="${ONE_LINE%%|*}"; DRV="${DRV#/dev/}"
		[ "$DRV" = "$get_device_RET" ] && continue # don't clobber source
		grep -m1 "$DRV" /proc/mounts >/dev/null && continue # mounted
		REMOV=''
		[ -f /sys/block/$DRV/removable ] && read REMOV < /sys/block/$DRV/removable
		[ "$REMOV" = "1" ] || continue # not stick
		DSIZE='0'
		[ -f /sys/block/$DRV/size ] && read DSIZE < /sys/block/$DRV/size
		[ "$DSIZE" = "0" ] && continue # not real
		echo "$SEL" >> "$STICK_LIST"
		echo "$DRV" >> "$STICK_LIST"
		DESC="${ONE_LINE##*|}"
		echo "$DESC" >> "$STICK_LIST"
		SEL='FALSE'
	done
	if [ ! -s "$STICK_LIST" ]; then
		if [ "$SRC_PART" ]; then
			error_exit "Will not overwrite source usb stick.
No other unmounted usb stick found."
		else
			error_exit "No unmounted usb stick found."
		fi
	fi
}

get_drv_name() {
	DRV_SPEC="$(yad $YAD_STD_OPTS --title "StickPup v${VER} - destination" --width=260 \
		--text "Puppy is written to the usb stick selected here.

Select a destination stick:" \
		--list --print-column=2 --radiolist --column=:RD --column=Drive --column=Description < $STICK_LIST)"
	[ $? -eq 0 ] || error_exit
	DRV_NAME="${DRV_SPEC%%|*}"
	rm "$STICK_LIST"
}

get_boot_type() {
	BOOT_TYPE='both'
#	BOOT_TYPE='uefi'
}

get_source() {
	SRC_SPEC="$(yad $YAD_STD_OPTS --title "StickPup v${VER} - Source type" --height=230 \
		--text "StickPup installs a single Puppy to a usb stick.

The usb stick is formated with a single <span foreground='purple'>fat32</span> partition.
The selected source Puppy is then installed on it.

Select the source type:" \
		--list --no-headers --print-column=3 --radiolist --column=:RD --column=:TXT --column=:TXT \
		TRUE '    ' 'iso' FALSE '    ' 'zip' FALSE '    ' 'directory' FALSE '    ' 'this')"
	[ $? -eq 0 ] || error_exit
	SRC_TYPE="${SRC_SPEC%%|*}"

	SRC_DIR=''; SRC_FN=''
	if [ "$SRC_TYPE" = "this" ]; then
		. /etc/rc.d/PUPSTATE
		#mainly to catch unplugged usb devices, but doing it for all
		for ONE_PARM in $(head -n1 /proc/cmdline); do
			case $ONE_PARM in
				psfspart=*) PSFSID="${ONE_PARM#*=}"; break ;;
				pdrv=*) PSFSID="${ONE_PARM#*=}"; break ;;
				pupsfs=*) PSFSID="${ONE_PARM#*=}"; break ;;
				pdev1=*) PSFSID="${ONE_PARM#*=}"; break ;;
			esac
		done
		if [ "$PSFSID" ]; then
			TMP_BLK="/tmp/${0##*/}_$$_blk_list.txt"
			busybox blkid | grep -v 'squashfs' | grep -v 'swap' | grep -v 'zram' > "$TMP_BLK"
			ID_PART="$(grep "=\"${PSFSID}\"" "$TMP_BLK" | cut -f1 -d':')"
			[ "$ID_PART" ] || error_exit "Puppy install partition is not available.
Probably due to unplugged usb boot device."
			SRC_PART="${ID_PART#/dev/}"
		else
			SRC_PART="${PUPSFS%%,*}"
		fi
		ensure_mounted "$SRC_PART"
		[ "$ensure_mounted_DID" ] && SRC_MTD="$ensure_mounted_MP"
		[ "$ensure_mounted_MP" ] || error_exit "Could not mount \"$SRC_PART\"."
		SRC_MP="$ensure_mounted_MP"
		SFS_FN="${SRC_MP}${PUPSFS##*,}"
		if [ -f "$SFS_FN" ]; then
			SRC_DIR="${SFS_FN%/*}"
			SRC_TYPE='directory'
			SUB_DIR="${SFS_FN##*/}"; SUB_DIR="${SUB_DIR#puppy_}"; SUB_DIR="${SUB_DIR%%_*}"
			boot_part_chk
		else
			error_exit "Puppy file \"$SFS_FN\" not found."
		fi
	elif [ "$SRC_TYPE" = "directory" ]; then
		SRC_DIR="$(yad $YAD_STD_OPTS --title "StickPup v${VER} - Source directory." \
			--file --directory --width=600 --height=460 \
			--text " Select the directory containing the Puppy files." \
			--filename="/mnt/")"
		[ $? -eq 0 ] || error_exit
		SFS_FN="$(find "$SRC_DIR" -maxdepth 1 -type f -name 'puppy_*.sfs')"
		[ "$SFS_FN" ] || error_exit "No Puppy files found in $SRC_DIR."
		SUB_DIR="${SFS_FN##*/}"; SUB_DIR="${SUB_DIR#puppy_}"; SUB_DIR="${SUB_DIR%%_*}"
	else
		SRC_FN="$(yad $YAD_STD_OPTS --title "StickPup v${VER} - Source file." \
			--file --file-filter "$SRC_TYPE files | *.$SRC_TYPE" --width=600 --height=460 \
			--text " Select the $SRC_TYPE file containing the Puppy files." \
			--filename="$HOME/")"
		[ $? -eq 0 ] || error_exit
		[ -d "$SRC_FN" ] && error_exit "No $SRC_TYPE file selected."
		[ "${SRC_FN##*.}" = "$SRC_TYPE" ] || error_exit "No $SRC_TYPE file selected."
		SUB_DIR="${SRC_FN##*/}"; SUB_DIR="${SUB_DIR%%-*}"; SUB_DIR="${SUB_DIR%%_*}"
	fi
}

confirm_choices() {
	if [ "$SRC_FN" ]; then
		SRC_DISP="$SRC_FN"
	else
		SRC_DISP="$SRC_DIR"
	fi
	yad $YAD_STD_OPTS --title "StickPup v${VER} - confirm" --width=260 \
		--text "About to format <span foreground='purple'><big>${DRV_NAME}</big></span> and install Puppy from:
<span foreground='purple'>$SRC_DISP</span>

<span foreground='red'>All current files on the destination usb stick will be lost</span>

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

format_drive() {
	gtkdialog-splash -bg yellow -close box -text "Partitioning and formating $DRV_NAME" &
	XPID=$!
	parted -s "/dev/$DRV_NAME" mklabel msdos
	[ $? -eq 0 ] || error_exit "failed to create partition tabel in ${DRV_NAME}"
	parted -s "/dev/$DRV_NAME" mkpart primary fat32 2048s -- -1
	[ $? -eq 0 ] || error_exit "failed to create partition in ${DRV_NAME}"
	sync
	mkfs.vfat -F 32 "/dev/${DRV_NAME}1"
	[ $? -eq 0 ] || error_exit "failed to create fat32 filesystem in ${DRV_NAME}1"
	parted -s "/dev/$DRV_NAME" set 1 boot on
	[ $? -eq 0 ] || error_exit "failed to set boot flag for ${DRV_NAME}1"
	sync
	kill -9 $XPID
}

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

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

DRV_NAME=''
BOOT_TYPE=''
SRC_TYPE=''
SRC_PART=''

XPID=''
SRC_DIR=''
SUB_DIR=''

grub2_chk

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

boot_part_chk

get_source

get_drv_name
[ "$DRV_NAME" ] || error_exit "No unmounted usb stick found."
diskSIZE=$(($(grep "${DRV_NAME}$" /proc/partitions | tr -s ' ' | cut -f4 -d' ') / 1024))
[ $diskSIZE -lt 400 ] && error_exit "${DRV_NAME} is ${diskSIZE}MiB, need 400MiB"
get_boot_type

confirm_choices

format_drive

[ -f "$CONFIG_FN" ] && . "$CONFIG_FN"

echo "SRC_TYPE='$SRC_TYPE'" > "$CACHE_FN"
echo "SRC_FN='$SRC_FN'" >> "$CACHE_FN"
echo "SRC_DIR='$SRC_DIR'" >> "$CACHE_FN"
echo "SFS_PART='${DRV_NAME}1'" >> "$CACHE_FN"
echo "SFS_DIR='/${SUB_DIR}'" >> "$CACHE_FN"
echo "XTRA_PARMS='$minPARMS'" >> "$CACHE_FN"
ERR_MSG="$("$EXE_DIR/frugalpup-dopupdir")"
[ $? -eq 0 ] || error_exit "frugalpup-dopupdir: $ERR_MSG"

echo "SFS_PART='${DRV_NAME}1'" > "$CACHE_FN"
echo "SFS_DIR='/${SUB_DIR}'" >> "$CACHE_FN"
echo "DEST_PART='${DRV_NAME}1'" >> "$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 "Puppy installed on <span foreground='purple'>$DRV_NAME</span>."

exit
