#!/bin/bash
# requires /usr/sbin/pdsk

export TEXTDOMAIN=bootflash
export OUTPUT_CHARSET=UTF-8

[ "`whoami`" != "root" ] && exec sudo -A ${0} ${@} #110505

if [ "$1" = "debug" ] ; then
	exec &>/tmp/${0##*/}.log ; set -x ; env #debug
	shift
fi

. /etc/rc.d/PUPSTATE
. /etc/DISTRO_SPECS

PARAM1=""
if [ $1 ] ; then
	probedisk -extended-usb -card-as-usbflash | grep usbflash | grep "/${1}|" || exit
	PARAM1="$1"
	USBDRV="$PARAM1"
fi

if [ "$USBDRV" = "" ];then
	FDS=$(probedisk -extended-usb -card-as-usbflash -plus-size -hr | grep usbflash)
	if [ -z "$FDS" ] ; then
		/usr/lib/gtkdialog/box_ok "Bootflash" error "$(gettext 'No USB drive plugged in')"
		exit 1
	fi
	echo "$FDS" | sed 's|/dev/||' | \
	while read USBINFO
	do
		IFS="|" read -r ONEUSB USBTYPE USBINFO USBSIZE <<< "$USBINFO"
		if [ "$USBSIZE" = "0" -o "$USBSIZE" = "0B" ] ; then
			continue # /dev/sdd|usbdrv|Multi Flash Reader|0
		fi
		echo "$ONEUSB \"Flash memory, ${USBINFO}, ${USBSIZE}\""
	done > /tmp/xselections$$
	xSELECTIONS="`cat /tmp/xselections$$ | tr '\n' ' ' | tr -s ' '`"
	rm -f /tmp/xselections$$
	CHOOSEDLG="Xdialog --wmclass \"gtkdialog2\" --title \"$(gettext 'BootFlash: make USB drive bootable')\" --no-cancel --stdout --menubox \"$(gettext 'Choose which drive to format:')\" 10 60 0 ${xSELECTIONS}"
	DRVSEL="`eval "$CHOOSEDLG"`"
	[ $? -ne 0 ] && exit
	USBDRV="$DRVSEL"
fi


#======================================================================
#                             FUNCTIONS
#======================================================================

# $1: device
ensure_unmounted() {
	umount $1 2>/dev/null ; sync ; sleep 1
	umount $2 2>/dev/null ; sync
	if [ "`mount | grep "^${1}"`" ] ; then
		/usr/lib/gtkdialog/box_ok "Bootflash" error "$(gettext "${USBDRV} is being used")" \
			"$(gettext "${USBDRV} please unmount all the drive partitions and run this script again")"
		exit 1
	fi
}

# $1: device
# $2: fileystem (f2fs) [optional, default vfat]
create_gpt_drv() {
	local XDEV=${1##*/}
	local XFSTYPE=vfat
	local XFSTYPE2=${2}

	ensure_unmounted /dev/${XDEV}
	#-- wipe_existing_partition_table_and_filesystem_signatures
	dd if=/dev/zero of=/dev/${XDEV} bs=1M count=10
	sync
	sleep 1

	# -- create_target_partition_table
	# parted
	if [ "$XFSTYPE2" ] ; then # f2fs
		parted --script -- \
			/dev/${XDEV} \
			mklabel gpt \
			mkpart primary fat32 4MiB 60MiB \
			mkpart primary ext2 100MiB 100%
	else
		parted --script -- \
			/dev/${XDEV} \
			mklabel gpt \
			mkpart primary fat32 4MiB 100%
	fi

	sync
	blockdev --rereadpt /dev/${XDEV}
	mkdosfs -F 32 -v /dev/${XDEV}1
	sleep 1
	case "$XFSTYPE2" in
		f2fs) mkfs.f2fs /dev/${XDEV}2 ;;
	esac
	sync

	blockdev --rereadpt /dev/${XDEV}
	sleep 4
}

# grub2 - make bootable
# $1: targetdir 
# $2: pmedia
copy_grub2_uefi_boot() {
	# includes some code from uefi-usb-installer (01micko)
	local HOMEDIR="$1"
	local PMEDIA="$2"
	GRUBDIR="/usr/share/grub2-efi"
	mkdir -p ${HOMEDIR}/EFI/boot
	if [ -f ${GRUBDIR}/grubia32.efi ] ; then
		cp ${GRUBDIR}/grubia32.efi ${HOMEDIR}/EFI/boot/bootia32.efi
	fi
	if [ -f ${GRUBDIR}/grubx64.efi ] ; then
		cp ${GRUBDIR}/grubx64.efi ${HOMEDIR}/EFI/boot/bootx64.efi
	elif [ -f $GRUBDIR/grubx64.efi.tar.xz ] ; then # old stuff
		tar -xJvf $GRUBDIR/grubx64.efi.tar.xz -C ${HOMEDIR}/EFI/boot/
		mv ${HOMEDIR}/EFI/boot/grubx64.efi ${HOMEDIR}/EFI/boot/bootx64.efi
	fi
	sync

	# grub.cfg
	[ "$PMEDIA" ] || PMEDIA=usbflash
	BOOTLABEL='puppy'
	sed -e "s/DISTRO_FILE_PREFIX/${DISTRO_FILE_PREFIX}/g" \
		-e "s/DISTRO_DESC/${DISTRO_FILE_PREFIX} ${DISTRO_VERSION}/g" \
		-e "s/#distrodesc#/${DISTRO_FILE_PREFIX} ${DISTRO_VERSION}/g" \
		-e "s/BOOTLABEL/${BOOTLABEL}/g"  \
		-e "s/pmedia=cd/pmedia=${PMEDIA}/g" \
		/usr/share/boot-dialog/grub.cfg > ${HOMEDIR}/grub.cfg

	if [ -f /usr/share/boot-dialog/puppy.png ] ; then
		cp -fv /usr/share/boot-dialog/puppy.png ${HOMEDIR}/splash.png
	else
		sed -i '/background_image/d' ${HOMEDIR}/grub.cfg
	fi
}

# efilinux - make bootable
# $1: targetdir 
# $2: pdrv
# $3: pmedia
copy_efilinux_uefi_boot() {
	local HOMEDIR="$1"
	local PDRV="$2"
	local PMEDIA="$3"

	mkdir -p ${HOMEDIR}/EFI/boot
	cp -f /usr/lib/efilinux/efilinux.efi ${HOMEDIR}/EFI/boot/bootx64.efi

	INITRD="initrd=\initrd.gz"
	[ -f ${SRCPATH}/ucode.cpio ] && INITRD="initrd=\ucode.cpio ${INITRD}"

	APPEND="pfix=fsck pmedia=${PMEDIA}"
	if [ ! "$FSTYPE2" ] ; then
		UUID=$(blkid -o export ${PDRV} | grep ^UUID= | cut -f 2 -d =)
		[ "$UUID" ] && APPEND="${APPEND} pupsfs=${UUID} psave=${UUID}"
	fi

	echo "-f \vmlinuz ${INITRD} ${APPEND}" > ${HOMEDIR}/EFI/boot/efilinux.cfg

	sync
}

# $1: directory
# $2: distro
# $3: pmedia
copy_g4dos_cd() {
	if [ ! -d "$1" ] ; then
		return 1
	fi

	cp -fv /usr/share/g4dos/pcd/* "$1"/ # deleted dir - obsolete code - delete this
	cp -fv /usr/share/boot-dialog/menu.lst "$1"/
	cp -fv /usr/share/boot-dialog/menu_phelp.lst "$1"/
	cp -fv /usr/share/boot-dialog/grldr "$1"/

	if [ "$2" ] ; then #distro
		if [ "$2" = "auto" ] ; then
			. /etc/DISTRO_SPECS
			sed -i "s%#distrodesc#%${DISTRO_NAME} ${DISTRO_VERSION}%" "$1"/menu.lst
		else
			sed -i "s%#distrodesc#%${2}%" "$1"/menu.lst
		fi
	fi
	if [ "$3" ] ; then #pmedia
		sed -i "s|pmedia=cd|pmedia=${3}|" "$1"/menu.lst
	fi

	# frugalpup
	if [ -f /usr/local/frugalpup/grub4dos.tar.xz ] ; then
		tar -C "$1"/ -xf /usr/local/frugalpup/grub4dos.tar.xz ./grldr
	fi

	if [ ! -f "$1"/grldr ] && [ -f /usr/lib/grub4dos/grldr ] ; then # grub4dosconfig
		cp /usr/lib/grub4dos/grldr "$1"/
	fi
}

# $1: drive
write_wee_mbr() {
	XDEV=${1##*/}
	BLOCKDEV=$1
	WEE_MBR='/usr/share/boot-dialog/wee.mbr'
	[ -f /usr/share/g4dos/wee.mbr ] && WEE_MBR='/usr/share/g4dos/wee.mbr' # moved - delete this
	if [ ! -f $WEE_MBR ] ; then
		echo "file not found: $WEE_MBR"
		exit 1
	fi
	cp ${WEE_MBR} /tmp/wee.mbr
	## Read disk signature and partition table from MBR
	## and write it to wee.mbr:
	dd if=${BLOCKDEV} bs=1 skip=439 count=72 2>/dev/null | \
		dd of=/tmp/wee.mbr bs=1 seek=439 conv=notrunc
	## backup MBR
	dd if=${BLOCKDEV} of=/tmp/${XDEV}.mbr bs=512 count=63
	## Write wee MBR to $MBR_DEV
	echo "Installing bootloader(Wee) on ${BLOCKDEV} ..."
	dd if=/tmp/wee.mbr of=${BLOCKDEV}
}

# create msdos partition table and 1 partition, then install wee.mbr
# $1 = drv
# $2 = XFSTYPE (vfat, ntfs, ext3, ext4)
# $3 = XFSTYPE2 (f2fs)  (optional - $2 becomes vfat)
create_bios_bootable_drv() {
	local XDEV=${1##*/}
	local XFSTYPE=$2
	local XFSTYPE2=$3

	ensure_unmounted /dev/${XDEV}
	#-- wipe_existing_partition_table_and_filesystem_signatures
	dd if=/dev/zero of=/dev/${XDEV} bs=1M count=10 #bs=512 count=1
	sync
	sleep 1

	# -- create_target_partition_table
	# parted
	if [ "$XFSTYPE2" ] ; then # f2fs
		XFSTYPE=vfat
		parted --script -- \
			/dev/${XDEV} \
			mklabel msdos \
			mkpart primary fat32 4MiB 60MiB \
			mkpart primary ext2 100MiB 100% \
			set 1 boot on
	else
		# https://rainbow.chard.org/2013/01/30/how-to-align-partitions-for-best-performance-using-parted/
		case "$XFSTYPE" in
			vfat) DEVTYPE=fat32 ; mkpart_end='-1s'    ;;
			ntfs) DEVTYPE=NTFS  ; mkpart_end='-1025s' ;; # Leave 512KiB==1024sector in traditional 512bytes/sector disk, disks with sector with more than 512bytes only result in partition size greater than 512KiB and is intentionally let-it-be.
			ext*) DEVTYPE=ext2  ; mkpart_end='-1s'    ;;
		esac
		#mkpart primary fat32 0% 100%
		parted --script -- \
			/dev/${XDEV} \
			mklabel msdos \
			mkpart primary ${DEVTYPE} 4MiB ${mkpart_end} \
			set 1 boot on
	fi
	sync
	sleep 1.5
	blockdev --rereadpt /dev/${XDEV}

	#-- create_target_partition
	if grep -q '64bit' /etc/mke2fs.conf ; then
		sed -i 's/64bit,//g' /etc/mke2fs.conf #remove 64bit flag
	fi

	case "$XFSTYPE" in
		vfat) mkdosfs -F 32 -v /dev/${XDEV}1 ;;
		ntfs) mkntfs -f /dev/${XDEV}1        ;;
		ext*) mkfs.${XFSTYPE} /dev/${XDEV}1   ;;
	esac
	sleep 1
	case "$XFSTYPE2" in
		f2fs) mkfs.f2fs /dev/${XDEV}2 ;;
	esac

	sync
	blockdev --rereadpt /dev/${XDEV}
	echo 'Wait 4 seconds for block device nodes to populate...'
	sleep 4
	sync
}

# syslinux - make bootable
# $1: targetdir 
# $2: pdrv
# $3: pmedia
# $4: fstype2
create_syslinux_conf() {
	local HOMEDIR="$1"
	local PDRV="$2"
	local PMEDIA="$3"
	local XFSTYPE2="$4"

	INITRD="initrd.gz"
	[ -f ${SRCPATH}/ucode.cpio ] && INITRD="ucode.cpio,${INITRD}"

	APPEND="pfix=fsck pmedia=${PMEDIA}"
	if [ ! "${XFSTYPE2}" ] ; then
		UUID=$(blkid -o export ${PDRV} | grep ^UUID= | cut -f 2 -d =)
		[ "$UUID" ] && APPEND="${APPEND} pupsfs=${UUID} psave=${UUID}"
	fi

	cat << EOF > ${HOMEDIR}/syslinux.cfg
DEFAULT puppy

LABEL puppy
	LINUX vmlinuz
	INITRD ${INITRD}
	APPEND ${APPEND}
EOF

	sync
}

#--

unmountcdfunc() {
	if [ "$CDDRIVE" -a "`mount | grep "^/dev/$CDDRIVE " | cut -f 3 -d ' '`" ];then
		umount /dev/$CDDRIVE "`mount | grep "^/dev/$CDDRIVE " | cut -f 3 -d ' '`"
	fi
	if [ "$ISO_MP" -a "`mount | grep " $ISO_MP "`" ] ; then
		umount $ISO_MP 2>/dev/null #iso mountpoint
	fi
}

locate_puppy_src_files() { # set $SRCPATH $CDDRIVE
	SRCPATH=""
	CDDRIVE=""
	ISO_MP=""
	MOUNT_ISO=""
	#-----
	if [ $PUPMODE -eq 2 ] ; then #full install
		MOUNT_ISO=1
	else
		PDEV1_IS_CD=$(probedisk /dev/${PDEV1} 2>/dev/null | grep '|optical|')
		PDEV1_MP=$(LANG=C mount | grep "^/dev/${PDEV1} " | awk '{print $3}')
		PDEV1_FS=$(busybox blkid /dev/${PDEV1} | grep -o ' TYPE=.*' | cut -f 2 -d '"')
		if [ "$PDEV1_MP" ] && [ ! "$PDEV1_FS" ] ; then # no fs?
			# hmm mounted but media not present?... removable drive (probably)
			umount $PDEV1_MP
			PDEV1_MP=""
		fi
		#--
		if [ ! "$PDEV1_FS" ] ; then
			# no partition fs
			PDEV1_FS="$DEV1FS" #DEV1FS is in /etc/rc.d/PUPSTATE
		fi
		if [ ! "$PDEV1_MP" ] ; then
			# not mounted
			mkdir -p /mnt/$PDEV1
			mount -t $PDEV1_FS /dev/$PDEV1 /mnt/$PDEV1
			if [ $? -eq 0 -a -f /mnt/${PDEV1}${PSUBDIR}/${DISTRO_PUPPYSFS} -a -f /mnt/${PDEV1}${PSUBDIR}/vmlinuz -a -f /mnt/${PDEV1}${PSUBDIR}/initrd.gz ] ; then
				SRCPATH=/mnt/${PDEV1}${PSUBDIR}
			else
				umount /mnt/$PDEV1 2>/dev/null
			fi
		else
			# already mounted
			if [ -f ${PDEV1_MP}${PSUBDIR}/${DISTRO_PUPPYSFS} -a -f ${PDEV1_MP}${PSUBDIR}/vmlinuz -a -f ${PDEV1_MP}${PSUBDIR}/initrd.gz ] ; then
				SRCPATH=${PDEV1_MP}${PSUBDIR}
			fi
		fi
		#--
		if [ -z "$SRCPATH" -a -n "$PDEV1_IS_CD" ] ; then # not found yet..
			# may need to insert CD..
			CDDRIVE=${PDEV1}
			CDDRVINFO=$(echo "$PDEV1_IS_CD" | cut -f 3 -d '|')
			Xdialog --wmclass "gtkdialog2" --left --title "$L_PUPPY_INSTALLER" \
			--msgbox "$(eval_gettext "Please insert the Puppy live-CD (if not already) \
  into the drive.\nNote, in case your PC has two CD/DVD drives, \
  Puppy is expecting\nthe live-CD to be inserted into $CDDRIVE, which is \
  described as:\n $CDDRVINFO \n\nAfter inserting live-CD, \
  click OK button...")" 0 0
			mkdir /mnt/${CDDRIVE} 2> /dev/null
			mount -t iso9660 /dev/${CDDRIVE} /mnt/${CDDRIVE} || umount /dev/${CDDRIVE}
			if [ -f /mnt/${CDDRIVE}${PSUBDIR}/${DISTRO_PUPPYSFS} ] ; then
				SRCPATH=/mnt/${CDDRIVE}${PSUBDIR}
			fi
		fi
	fi
	#-----
	if [ ! "$SRCPATH" ] ; then
		MOUNT_ISO=1 #last resort..
	fi
	#-----
	if [ "$MOUNT_ISO" ] ; then
		ISO_MP=/mnt/iso_file
		cd $HOME
		ISO_FILE=$(/usr/lib/gtkdialog/file_chooser "ISO File" "$(gettext "Please select a Puppy live-CD .iso file for $DISTRO_NAME $DISTRO_VERSION ")")
		[ $? -ne 0 ] && exit 1
		umount ${ISO_MP} 2>/dev/null
		mkdir -p ${ISO_MP}
		mount -t iso9660 -o loop ${ISO_FILE} ${ISO_MP}
		#--
		if [ -f ${ISO_MP}${PSUBDIR}/${DISTRO_PUPPYSFS} ] ; then
			SRCPATH=${ISO_MP}${PSUBDIR}
		elif [ -f ${ISO_MP}/${DISTRO_PUPPYSFS} ] ; then
			SRCPATH=${ISO_MP}
		else
			umount ${ISO_MP} 2>/dev/null
			ISO_MP=""
		fi
		#--
	fi
	#===============================
	#sanity check...
	if [ ! -f ${SRCPATH}/${DISTRO_PUPPYSFS} ];then #v3.01 v424 100913
		unmountcdfunc
		Xdialog --wmclass "gtkdialog2" --left \
			--title "$(gettext 'ERROR')" --msgbox "`eval_gettext \"Oh dear, a 'sanity check' has failed.\
 \nThis file: \\\$SRCPATH/\\\${DISTRO_PUPPYSFS}\ndoes not exist.\nThe above \
 is supposed to be path-to-where-puppy-files-are/\\\${DISTRO_PUPPYSFS}\
 \nClick OK button to quit...\"`" 0 0
		exit
	fi
} #end locate_puppy_src_files function.

#=================================================================
#                     MAIN DIALOG
#=================================================================

create_dlg_item() { # title desc icon exit
	echo '
    <hbox space-expand="true" space-fill="true">
      <text space-expand="false" space-fill="false"><label>""</label></text>
      <text xalign="0" use-markup="true" space-expand="true" space-fill="true"><label>"'"${1}
${2}"'"</label></text>
      <vbox space-expand="false" space-fill="false">
        <button>
          '"`/usr/lib/gtkdialog/xml_button-icon ${3} big`"'
          <action type="exit">'${4}'</action>
        </button>
      </vbox>
    </hbox>
    <hseparator></hseparator>'
}

if [ "$(ls /usr/share/grub2-efi/grub*.efi* 2>/dev/null)" ] ; then
	UEFI_USB_INSTALLER=$(
		create_dlg_item "$(gettext '<b>Create UEFI USB (GPT / GRUB2)</b>')" \
			"$(gettext 'For UEFI-enabled machines booting in UEFI mode. Installs the running system. Not compatible with old BIOS')" \
			install_options.svg 1
	)
fi

if [ -f /usr/lib/efilinux/efilinux.efi ] ; then
	EFILINUX_USB_INSTALLER=$(
		create_dlg_item "$(gettext '<b>Create UEFI USB (GPT / efilinux)</b>')" \
			"$(gettext 'For UEFI-enabled machines booting in UEFI mode. Installs the running system. Not compatible with old BIOS')" \
			install_options.svg 5
	)
fi

if command -v syslinux > /dev/null && [ -f /usr/lib/SYSLINUX/mbr.bin ] ; then
	SYSLINUX_USB_INSTALLER=$(
		create_dlg_item "$(gettext '<b>Create syslinux USB (MBR - BIOS)</b>')" \
			"$(gettext 'Does not support UEFI. Installs the running system. For computers booting with BIOS.')" \
			install_options.svg 6
	)
fi

if [ -d /usr/share/g4dos -o -f /usr/local/frugalpup/grub4dos.tar.xz -o -f /usr/lib/grub4dos/grldr ] ; then
	GRUB4DOS_USB_INSTALLER=$(
		create_dlg_item "$(gettext '<b>Create grub4dos USB (MBR - BIOS)</b>')" \
			"$(gettext 'Does not support UEFI. Installs the running system. For computers booting with BIOS.')" \
			install_options.svg 2
	)
fi

export ASKDIALOG='
<window height-request="600" width-request="800" title="'"Bootflash $USBDRV"'" icon-name="gtk-preferences">
<vbox scrollable="true">
  <frame Bootflash '$USBDRV'>
    '"`/usr/lib/gtkdialog/xml_info 0 flashcard_usb.svg 48 "$(gettext "This tool allows to quickly create a bootable usb drive ready to use. Be aware that ALL DATA ON THE USB DRIVE WILL BE LOST")"`"'

    '${UEFI_USB_INSTALLER}'

    '${EFILINUX_USB_INSTALLER}'

    '${GRUB4DOS_USB_INSTALLER}'

    '${SYSLINUX_USB_INSTALLER}'

    '$(create_dlg_item "$(gettext '<b>Write .img[.gz|.xz] file to USB drive</b>')" \
		"$(gettext "IMG files meant to be written to usb sticks/SD cards...")" \
		flashcard_usb_2.svg 3
		)'

    '$(create_dlg_item "$(gettext '<b>Write Hybrid ISO file to USB drive</b>')" \
		"$(gettext "It's probably only useful if you want to try/install Linux distros that provide hybrid ISOs.")" \
		cd_burn.svg 4
		)'

  </frame>
  
    <hbox space-expand="false" space-fill="false">
     <button>
       '"`/usr/lib/gtkdialog/xml_button-icon quit`"'
       <label>'$(gettext 'Quit')'</label>
       <action type="exit">EXIT</action>
     </button>
    </hbox>

  </vbox>
</window>'
#echo "$ASKDIALOG" > /tmp/bootflash.main.xml #debug
. /usr/lib/gtkdialog/xml_info gtk #build bg_pixmap for gtk-theme
RETVAL="`gtkdialog --center -p ASKDIALOG 2>/dev/null`"
eval "$RETVAL"

# check f2fs support
if [ "$(cat /proc/filesystems  | grep f2fs)" ] ; then
	if type mkfs.f2fs >/dev/null 2>&1 ; then
		F2FS_DLG=$(create_dlg_item "$(gettext '<b>FAT32 partition + F2FS partition</b>')" \
		"$(gettext 'Enables use of F2FS partition')" \
		install_options.svg 15)
	fi
fi

case $EXIT in
	1)
		#========================
		#    UEFI - GRUB2
		#========================
		BOOTLOADER=grub2
		FSTYPE=vfat
		export UEFI_DIALOG='<window title="'"BootFlash: $USBDRV"'" icon-name="gtk-preferences">
<vbox>
    '$(/usr/lib/gtkdialog/xml_info fixed execute_yes.svg 30 "$(gettext 'The intention of BootFlash is to make a USB memory stick (Flash drive) bootable.. then to install Puppy on it')")'

	'$(create_dlg_item "$(gettext '<b>FAT32 GPT UEFI</b>')" \
		"$(gettext 'Create FAT32 partition and install grub2')" \
		install_options.svg 11
		)'

	'${F2FS_DLG}'

    <hbox homogeneous="true" space-expand="true" space-fill="true">
       <text use-markup="true" space-expand="true" space-fill="true">
         <label>"<span fgcolor='"'#821811'"'><b>'$(gettext "THIS WILL DESTROY ALL DATA ON ${USBDRV}")'</b></span>"</label>
       </text>
    </hbox>
    <hseparator></hseparator>

    <hbox space-expand="false" space-fill="false">
     <button>
       '"`/usr/lib/gtkdialog/xml_button-icon quit`"'
       <label>'$(gettext 'Quit')'</label>
       <action type="exit">EXIT</action>
     </button>
    </hbox>

  </vbox>
</window>'
		. /usr/lib/gtkdialog/xml_info gtk
		#echo "$UEFI_DIALOG" > /tmp/bootflash.uefi.xml #debug
		RETPARAMS="`gtkdialog --center --program=UEFI_DIALOG`"
		eval "$RETPARAMS"
		case $EXIT in
			11) FSTYPE='vfat' ;;
			15) FSTYPE='vfat' ; FSTYPE2='f2fs' ;;
			*) exit ;;
		esac
		;;

	5)
		#========================
		#    UEFI - efilinux
		#========================
		BOOTLOADER=efilinux
		export UEFI_DIALOG='<window title="'"BootFlash: $USBDRV"'" icon-name="gtk-preferences">
<vbox>
    '$(/usr/lib/gtkdialog/xml_info fixed execute_yes.svg 30 "$(gettext 'The intention of BootFlash is to make a USB memory stick (Flash drive) bootable.. then to install Puppy on it')")'

	'${F2FS_DLG}'

	'$(create_dlg_item "$(gettext '<b>FAT32 GPT UEFI</b>')" \
		"$(gettext 'Create FAT32 partition and install efilinux')" \
		install_options.svg 11
		)'

    <hbox homogeneous="true" space-expand="true" space-fill="true">
       <text use-markup="true" space-expand="true" space-fill="true">
         <label>"<span fgcolor='"'#821811'"'><b>'$(gettext "THIS WILL DESTROY ALL DATA ON ${USBDRV}")'</b></span>"</label>
       </text>
    </hbox>
    <hseparator></hseparator>

    <hbox space-expand="false" space-fill="false">
     <button>
       '"`/usr/lib/gtkdialog/xml_button-icon quit`"'
       <label>'$(gettext 'Quit')'</label>
       <action type="exit">EXIT</action>
     </button>
    </hbox>

  </vbox>
</window>'
		. /usr/lib/gtkdialog/xml_info gtk
		#echo "$UEFI_DIALOG" > /tmp/bootflash.uefi.xml #debug
		RETPARAMS="`gtkdialog --center --program=UEFI_DIALOG`"
		eval "$RETPARAMS"
		case $EXIT in
			11) FSTYPE='vfat' ;;
			15) FSTYPE='vfat' ; FSTYPE2='f2fs' ;;
			*) exit ;;
		esac
		;;

	2)
		#========================
		#        GRUB4DOS
		#========================
		export GRUB4DOS_DIALOG='<window title="'"BootFlash: $USBDRV"'" icon-name="gtk-preferences">
<vbox>
    '$(/usr/lib/gtkdialog/xml_info fixed execute_yes.svg 30 "$(gettext 'The intention of BootFlash is to make a USB memory stick (Flash drive) bootable.. then to install Puppy on it')")'

	'${F2FS_DLG}'

	'$(create_dlg_item "$(gettext '<b>FAT32 partition + grub4dos</b>')" \
		"$(gettext 'Create FAT32 partition and install grub4dos')" \
		install_options.svg 11
		)'

    '$(create_dlg_item "$(gettext '<b>EXT4 partition + grub4dos</b>')" \
		"$(gettext 'Create ext4 partition and install grub4dos')" \
		install_options.svg 13
		)'

    '$(create_dlg_item "$(gettext '<b>EXT3 partition + grub4dos</b>')" \
		"$(gettext 'Create ext3 partition and install grub4dos')" \
		install_options.svg 14
		)'

	'$(create_dlg_item "$(gettext '<b>NTFS partition + grub4dos</b>')" \
		"$(gettext 'Create NTFS partition and install grub4dos')" \
		install_options.svg 12
		)'

    <hbox homogeneous="true" space-expand="true" space-fill="true">
       <text use-markup="true" space-expand="true" space-fill="true">
         <label>"<span fgcolor='"'#821811'"'><b>'$(gettext "THIS WILL DESTROY ALL DATA ON ${USBDRV}")'</b></span>"</label>
       </text>
    </hbox>
    <hseparator></hseparator>

    <hbox space-expand="false" space-fill="false">
     <button>
       '"`/usr/lib/gtkdialog/xml_button-icon quit`"'
       <label>'$(gettext 'Quit')'</label>
       <action type="exit">EXIT</action>
     </button>
    </hbox>

  </vbox>
</window>'
	. /usr/lib/gtkdialog/xml_info gtk
		#echo "$GRUB4DOS_DIALOG" > /tmp/bootflash.grub4dos.xml #debug
		RETPARAMS="`gtkdialog --center --program=GRUB4DOS_DIALOG`"
		eval "$RETPARAMS"

		BOOTLOADER='grub4dos'
		case $EXIT in
			13) FSTYPE='ext4' ;;
			14) FSTYPE='ext3' ;;
			12) FSTYPE='ntfs' ;;
			11) FSTYPE='vfat' ;;
			15) FSTYPE='vfat' ; FSTYPE2='f2fs' ;;
			*) exit ;;
		esac
		;;

	6)
		#========================
		#    SYSLINUX
		#========================
		BOOTLOADER=syslinux
		export SYSLINUX_DIALOG='<window title="'"BootFlash: $USBDRV"'" icon-name="gtk-preferences">
<vbox>
    '$(/usr/lib/gtkdialog/xml_info fixed execute_yes.svg 30 "$(gettext 'The intention of BootFlash is to make a USB memory stick (Flash drive) bootable.. then to install Puppy on it')")'

	'${F2FS_DLG}'

	'$(create_dlg_item "$(gettext '<b>FAT32 partition + syslinux</b>')" \
		"$(gettext 'Create FAT32 partition and install syslinux')" \
		install_options.svg 11
		)'

    <hbox homogeneous="true" space-expand="true" space-fill="true">
       <text use-markup="true" space-expand="true" space-fill="true">
         <label>"<span fgcolor='"'#821811'"'><b>'$(gettext "THIS WILL DESTROY ALL DATA ON ${USBDRV}")'</b></span>"</label>
       </text>
    </hbox>
    <hseparator></hseparator>

    <hbox space-expand="false" space-fill="false">
     <button>
       '"`/usr/lib/gtkdialog/xml_button-icon quit`"'
       <label>'$(gettext 'Quit')'</label>
       <action type="exit">EXIT</action>
     </button>
    </hbox>

  </vbox>
</window>'
		. /usr/lib/gtkdialog/xml_info gtk
		RETPARAMS="`gtkdialog --center --program=SYSLINUX_DIALOG`"
		eval "$RETPARAMS"
		case $EXIT in
			15) FSTYPE='vfat' ; FSTYPE2='f2fs' ;;
			11) FSTYPE='vfat' ;;
			*) exit ;;
		esac
		;;

	3)
		#========================
		#   DD IMG TO USB DRV
		#========================
		img_file=$(/usr/lib/gtkdialog/file_chooser --last-path "Select *.img / *.img.gz / *.img.xz file")
		if [ ! "$img_file" ] ; then
			exit
		fi
		case $img_file in *.img|*.img.gz|*.img.xz) ok=1 ;;
			*) exec /usr/lib/gtkdialog/box_ok "Error" error "$(gettext 'Only .img/.img.gz/img.xz are supported..')" ;;
		esac
		MYSELECTION="`echo "$xSELECTIONS" | grep "^${USBDRV} " | tr '"' ' ' | tr -s ' '`" #'geany
		/usr/lib/gtkdialog/box_yesno --warning --yes-label "$(gettext 'Write IMG to USB')" \
			--no-label "$(gettext 'Cancel')" "$(gettext 'Write IMG to USB')" \
			"IMG: ${img_file##*/}" \
			"USB: /dev/${MYSELECTION}"
		[ $? -ne 0 ] && exit
		echo 'pdsk img2flash "'${img_file}'" /dev/'${USBDRV}'
if [ $? -eq 0 ] ; then
	/usr/lib/gtkdialog/box_ok Done info "Finished writing IMG file to /dev/'${USBDRV}'" "" "Hopefully no errors occurred.."
else
	/usr/lib/gtkdialog/box_ok Error error "Error writing img file to drive"
fi
' > /tmp/write_img_file_usb_drv_$$
		xterm -title "Writing IMG to /dev/${USBDRV}" -e sh /tmp/write_img_file_usb_drv_$$
		rm -f /tmp/write_img_file_usb_drv_$$
		exit
		;;

	4)
		#========================
		#   DD ISO TO USB DRV
		#========================
		iso_file=$(/usr/lib/gtkdialog/file_chooser --last-path "Select ISO file")
		if [ ! "$iso_file" ] ; then
			exit
		fi
		case $iso_file in *.[iI][sS][oO]) ok=1 ;;
			*) exec /usr/lib/gtkdialog/box_ok "Error" error "$(gettext 'You did not select an ISO file..')" ;;
		esac
		res=$(yad --title="Bootflash - $USBDRV" --window-icon="gtk-yes" \
			--button=gtk-ok:0 --button="Don't recover empty space":1 \
			--center --sticky --on-top --fixed --form \
			--field="$(gettext 'We can also try to make the extra space usable again and create a new partition. This is not guaranteed to work. Select filesystem:'):LBL" "" \
			--field="$(gettext 'Filesystem'):CB" "ext4!ntfs!fat")
		FS_TYPE=$(echo $res | cut -f 2 -d "|")
		#---
		MYSELECTION="`echo "$xSELECTIONS" | grep "^${USBDRV} " | tr '"' ' ' | tr -s ' '`" #'geany
		/usr/lib/gtkdialog/box_yesno --warning --yes-label "$(gettext 'Write ISO to USB')" \
			--no-label "$(gettext 'Cancel')" "$(gettext 'Write ISO to USB')" \
			"ISO: ${iso_file##*/}" \
			"USB: /dev/${MYSELECTION}"
		[ $? -ne 0 ] && exit
		echo 'pdsk iso2flash "'${iso_file}'" /dev/'${USBDRV}' '${FS_TYPE}'
if [ $? -eq 0 ] ; then
	/usr/lib/gtkdialog/box_ok "Done" info "'$(gettext "Finished writing ISO file to")' /dev/'${USBDRV}'" "" "Hopefully no errors occurred.."
else
	/usr/lib/gtkdialog/box_ok Error error "Error writing ISO file to drive"
fi
' > /tmp/write_iso_file_usb_drv_$$
		xterm -title "Writing ISO to /dev/${USBDRV}" -e sh /tmp/write_iso_file_usb_drv_$$
		rm -f /tmp/write_iso_file_usb_drv_$$
		exit
		;;

	*)
		exit ;;
esac

ensure_unmounted /dev/${USBDRV}

#reconfirm correct drv choice...
MYSELECTION="`echo "$xSELECTIONS" | grep "^${USBDRV} " | tr '"' ' ' | tr -s ' '`" #'geany
/usr/lib/gtkdialog/box_yesno --no-first --yes-label "$(gettext 'OK')" --no-label "$(gettext 'Cancel')" "BootFlash" \
	"$(gettext 'Please reconfirm that this is the USB drive that you want to format:')" \
	"<b>${MYSELECTION}</b>" \
	"`gettext "Please also reconfirm that you want to use BootFlash to reformat the drive (and install Puppy)."`" \
	"`gettext "Click 'OK' to continue, 'Cancel' to quit:"`"
	[ $? -ne 0 ] && exit

#make sure not mounted...
while [ "`mount | grep "^/dev/$DRVSEL "`" != "" ];do
	/usr/lib/gtkdialog/box_yesno --yes-first --yes-label "$(gettext 'OK')" --no-label "$(gettext 'Cancel')" "BootFlash" \
	"$(printf "$(gettext '<b>Drive %s is still mounted. Please unmount it before continuing. If the drive has multiple partitions, are they all unmounted?</b>')" "${DRVSEL}")" \
	"$(gettext 'Note: click on the appropriate mounted desktop drive icon, and you will receive an offer to unmount it.')" \
	"$(gettext 'Click 'OK' to continue, 'Cancel' to quit:')"
	[ $? -ne 0 ] && exit
	sleep 1
done


#======================================================================
#            DRIVE PARTITIONING / INSTALLATION
#======================================================================

/usr/lib/gtkdialog/box_splash -close never -text "$(printf "$(gettext 'Please wait, formatting %s drive...')" "${USBDRV}")" &
X1PID=$!

if [ "$BOOTLOADER" = "grub4dos" ] ; then
	create_bios_bootable_drv ${USBDRV} ${FSTYPE} ${FSTYPE2}
	write_wee_mbr /dev/${USBDRV##*/} #install wee.mbr
elif [ "$BOOTLOADER" = "syslinux" ] ; then
	create_bios_bootable_drv ${USBDRV} ${FSTYPE} ${FSTYPE2}
	dd if=/usr/lib/SYSLINUX/mbr.bin of=/dev/${USBDRV##*/}
elif [ "$BOOTLOADER" = "grub2" -o "$BOOTLOADER" = "efilinux" ] ; then
	create_gpt_drv ${USBDRV} ${FSTYPE2}
else
	exit 1
fi

# need to refresh desktop drive icons(s)...
echo change > /sys/block/${USBDRV}/uevent
sleep 2

kill $X1PID

if [ -z "$SRCPATH" ] ; then
	locate_puppy_src_files
fi

#-----------------------------------------------------------------------

PBOOTPART=${USBDRV}1
mkdir -p /mnt/${PBOOTPART}
mount -t $FSTYPE /dev/${PBOOTPART} /mnt/${PBOOTPART}

if [ "`mount | grep "/dev/${PBOOTPART}"`" = "" ];then
	/usr/lib/gtkdialog/box_ok "Bootflash" error "$(gettext 'Error mounting USB drive')"
	exit
fi

/usr/lib/gtkdialog/box_splash -close never -text "$(gettext 'Please wait, copying files...')" &
X1PID=$!

if [ "`cat /sys/block/$USBDRV/removable`" = "1" ] ; then
	PMEDIA="usbflash"
else
	PMEDIA="usbhd"
fi

if [ "$BOOTLOADER" = "grub4dos" ] ; then
	copy_g4dos_cd /mnt/${PBOOTPART} auto ${PMEDIA}
elif [ "$BOOTLOADER" = "syslinux" ] ; then
	syslinux /dev/${USBDRV}1
	create_syslinux_conf /mnt/${PBOOTPART} /dev/${PBOOTPART} ${PMEDIA} ${FSTYPE2}
elif [ "$BOOTLOADER" = "grub2" ] ; then
	copy_grub2_uefi_boot /mnt/${PBOOTPART} ${PMEDIA}
elif [ "$BOOTLOADER" = "efilinux" ] ; then
	copy_efilinux_uefi_boot /mnt/${PBOOTPART} /dev/${PBOOTPART} ${PMEDIA}
fi

FILES2COPY="vmlinuz
initrd.gz
ucode.cpio
${DISTRO_PUPPYSFS}
${DISTRO_ZDRVSFS}
${DISTRO_FDRVSFS}
${DISTRO_ADRVSFS}
${DISTRO_YDRVSFS}
${DISTRO_BDRVSFS}
kbuild-`uname -r`.sfs
devx_${DISTRO_FILE_PREFIX}_${DISTRO_VERSION}.sfs
docx_${DISTRO_FILE_PREFIX}_${DISTRO_VERSION}.sfs
nlsx_${DISTRO_FILE_PREFIX}_${DISTRO_VERSION}.sfs"

#-------------------------
if [ "${FSTYPE2}" ] ; then # fat32 + f2fs
	PBOOTPART=${USBDRV}2
	mkdir -p /mnt/${PBOOTPART}
	mount -t $FSTYPE2 /dev/${PBOOTPART} /mnt/${PBOOTPART}
	if [ "`mount | grep "/dev/${PBOOTPART}"`" = "" ];then
		/usr/lib/gtkdialog/box_ok "Bootflash" error "$(gettext 'Error mounting USB drive')"
		exit
	fi
	#-
	cp -fv ${SRCPATH}/vmlinuz /mnt/${USBDRV}1/
	cp -fv ${SRCPATH}/initrd.gz /mnt/${USBDRV}1/
	[ -f ${SRCPATH}/ucode.cpio ] && cp -fv ${SRCPATH}/ucode.cpio /mnt/${USBDRV}1/
	#- get partition UUID
	UUID=$(busybox blkid /dev/${USBDRV}2 | grep -o ' UUID=".*' | cut -f2 -d '"')
	if [ "$UUID" ] ; then
		# need to alter bootmenu
		if [ -f /mnt/${USBDRV}1/menu.lst ] ; then
			SEDFILES="/mnt/${USBDRV}1/menu.lst"
		fi
		if [ -f /mnt/${USBDRV}1/grub.cfg ] ; then
			SEDFILES="$SEDFILES /mnt/${USBDRV}1/grub.cfg"
		fi
		if [ -f /mnt/${USBDRV}1/EFI/boot/efilinux.cfg ] ; then
			SEDFILES="$SEDFILES /mnt/${USBDRV}1/EFI/boot/efilinux.cfg"
		fi
		if [ -f /mnt/${USBDRV}1/syslinux.cfg ] ; then
			SEDFILES="$SEDFILES /mnt/${USBDRV}1/syslinux.cfg"
		fi
		PUPSFS="pupsfs=$UUID psave=$UUID"
		sed -i \
			-e "s%pmedia=cd%pmedia=cd $PUPSFS%" \
			-e "s%pmedia=usbhd%pmedia=usbhd $PUPSFS%" \
			-e "s%pmedia=usbflash%pmedia=usbflash $PUPSFS%" \
			${SEDFILES}
	fi
	FILES2COPY=$(echo "$FILES2COPY" | grep -v 'vmlinuz|initrd.gz')
fi
#-------------------------

for i in ${FILES2COPY} ; do
	if [ -f ${SRCPATH}/${i} ] ; then
		cp -fv ${SRCPATH}/${i} /mnt/${PBOOTPART}/
	fi
done

sync

umount /mnt/${USBDRV}1
if [ "${FSTYPE2}" ] ; then
	umount /mnt/${USBDRV}2
fi
unmountcdfunc
kill $X1PID

/usr/lib/gtkdialog/box_ok "$(gettext 'BootFlash: Puppy installed')" complete \
 "<b>$(gettext 'Puppy installed!')</b>" \
 "<b>$(gettext 'USB drive now (hopefully) bootable!')</b>" \
 "$(gettext 'The desktop drive icons should have been updated, so you can click on them to check that everything looks right. Then reboot and find out for sure...')"

### END ###
