#! /bin/bash

#variables
TMPDIR=/var/tmp
XZIMG=$TMPDIR/Manjaro-ARM.img.xz
IMG=$TMPDIR/Manjaro-ARM.img
root=`mount | grep "on / " | cut -c "6-12"`

# Functions
msg() {
	ALL_OFF="\e[1;0m"
	BOLD="\e[1;1m"
	GREEN="${BOLD}\e[1;32m"
		local mesg=$1; shift
		printf "${GREEN}==>${ALL_OFF}${BOLD} ${mesg}${ALL_OFF}\n" "$@" >&2
 }

flash_emmc(){
 
	#DD image to selected device
	msg "Flashing Image to eMMC. This will take some time (3-5 minutes)......"
	xzcat $XZIMG | dd of=$EMMC bs=4M status=progress
	sync

	# prompt for user to continue. Again, to catch errors if occurd
    msg "Flash Complete"	
	read -n 1 -s -r -p "Press any key to continue"

	#quick notification to say its finished and to reboot
	dialog --title "Manjaro-ARM eMMC Flasher"\
               --msgbox "Flash is complete. The system will shut down so you can remove the SDCard" 10 70

	 clear
	 msg "Poweroff in 5 seconds..."
	 sleep 1
	 echo "4..."
	 sleep 1
	 echo "3..."
	 sleep 1
	 echo "2..."
	 sleep 1
	 echo "1..."
	 sleep 1
	 poweroff
}


userprompts(){
	let i=0
	W=()
	while read -r line; do
		let i=$i+1
		W+=($line "")
	done < <( lsblk -dn -o NAME )
	
	EMMC=$(dialog --title "Manjaro-ARM eMMC Flasher" \
	--menu "Choose your eMMC device - Be sure the correct drive is selected!
		
Currently, the booted sdcard is at \"$root\"" 20 70 10 \
	"${W[@]}" 3>&2 2>&1 1>&3)

     	res=$?
	case $res in
		0) 
 			# add /dev/ to the selected option above
			DEV_NAME=$EMMC
			EMMC=/dev/$EMMC
 			if [[ -f $XZIMG ]]; then
				clear
				flash_emmc
 			else
				clear
				msg "Image does not exists...."

 			fi;;
 	
		1) clear; msg "Installation aborted..."; exit 1;;
		255) clear; msg "Installation aborted..."; exit 1;;
		esac
}

# Kill bootsplash so the script can be seen
echo off > /sys/devices/platform/bootsplash.0/enabled

# Using Dialog to ask for user input for variables
	dialog --clear --title "Manjaro-ARM eMMC Flasher" \
    	       --yesno "The ONLY purpose of this image is to flash Manjaro-ARM to your internal eMMC card (or other internal storage). If this is not what is expected, please download and flash the correct image to your SDCard.
    
This will destroy all data currently on the eMMC. Please proceed with caution.

Do you want to proceed" 20 100 \
    3>&1 1>&2 2>&3 3>&-

	response=$?
	case $response in
		0) clear; userprompts;;
		1) clear; msg "Installation aborted..."; exit 1;;
		255) clear; msg "Installation aborted..."; exit 1;;
	esac


