#!/bin/bash
source /etc/zefie/core/variables
source /etc/zefie/core/dialogs
source /etc/zefie/core/functions

log "Process started at $(date)"

get_kernel_boot_params

if [ ! -b "$DESTDEV" ] || [ ! -b "$USBDEV" ]; then
	log "Could not read device data from kernel command line"
	NODEVS=1
fi

if [ -b "${USBDEV}" ]; then
	initial_scan_image_folder
fi

start_menu

log "Searching for destination device at ${DESTDEV}..."
progress_dialog "${OSNAME}: Preparing Devices" "Searching for destination device at ${DESTDEV}" 0

if [ ! -b "${DESTDEV}" ]; then
	show_error "Failed to find desintation device"
fi

log "Found destination device"

if [ "${DORESTORE}" == "1" ] || [ "${DOPARTITION}" == "1" ]; then
	progress_dialog "${OSNAME}: Preparing Devices" "Mounting USB device ${USBDEV}..." 25
	mount_usb "${USBDEV}" "${USBMNT}"
fi

if [ "${DOPARTITION}" == "1" ] || [ "${DOWIPE}" == "1" ] ; then
	if [ "$ISEMMC" == "1" ]; then
		log "Securely erasing all data on eMMC..."
		progress_dialog "${OSNAME}: Preparing Devices" "Secure erasing eMMC..." 50
		DISKSIZE=$(fdisk --bytes -l "${DESTDEV}" | /usr/bin/grep Disk | /usr/bin/grep bytes | cut -d' ' -f5)
		re='^[0-9]+$'
		if ! [[ $DISKSIZE =~ $re ]] ; then
			ISERROR=1
			log "Error getting size of ${DESTDEV} (got ${DISKSIZE}), expected size in bytes"
		else
			secure_erase_dev "${DESTDEV}" 0 "${DISKSIZE}"
			check_result $?
		fi
	else
		log "Clearing partition table on disk..."
		progress_dialog "${OSNAME}: Preparing Devices" "Clearing partition table on disk..." 50
		sgdisk --zap-all "${DESTDEV}" 2>>${LOGFILE} 1>>${LOGFILE}
		check_result $?
	fi
	log "Refreshing partitions..."
	progress_dialog "${OSNAME}: Preparing Devices" "Refreshing partititon table..." 75
	blockdev --flushbufs --rereadpt "${DESTDEV}" 2>>${LOGFILE} 1>>${LOGFILE}
fi

if [ "${DOPARTITION}" == "1" ]; then
	log "Restoring partition table from ${SGDPART}"
	progress_dialog "${OSNAME}: Preparing Devices" "Restoring partititon table with sgdisk binary table..." 85
	sgdisk -l "${SGDPART}" "${DESTDEV}" 2>>${LOGFILE} 1>>${LOGFILE}

	log "Refreshing partitions..."
	progress_dialog "${OSNAME}: Preparing Devices" "Refreshing partititon table..." 100
	partprobe "${DESTDEV}" 2>>${LOGFILE} 1>>${LOGFILE}
fi

if [ "${DORESTORE}" == "1" ]; then
	restore_all_partitions
fi

umount_dev "${USBDEV}"
log "Process ended at $(date)"

end_menu $ISERROR

exit 0;
