#!/bin/sh

umount_disk() {
local i=1
while true
do
if [ "$(fdisk -l | grep -o "$diskSelect$i")" == "$diskSelect$i" ]; then echo "Unmounting $diskSelect$i"; umount "$diskSelect$i"; let i=$i+1; else return; fi
done
}

make_table() {
echo -n "Creating a new GPT disklabel.."
(
echo "g"
echo "w"
) | fdisk "$diskSelect" > /dev/null
echo "Done."
}

make_part() {
echo -n "Creating a new partition 1 of type 'Linux filesystem'.."
(
echo "n"
echo "1"
echo
echo
echo "w"
) | fdisk "$diskSelect" > /dev/null
echo "Done."
}

format_part() {
echo "Creating ext4 filesystem.." 
mkfs.ext4 -F -O^64bit -L "$partLabel" "$diskSelect"1  > /dev/null
echo "Done."
}

select_disk() {
while true
do
echo -n "Input the number of the drive that you need to format: "
read userInput
diskSelect=$(fdisk -l | grep "Disk /dev/sd" | sed -n "$userInput"p)
if [ "$diskSelect" == "" ]; then echo "Incorrect input!"; else diskSelect=${diskSelect:5:8}; echo "$diskSelect was selected."; return; fi
done
}


show_disks() {
while true
do
if [ "$(ls /dev | grep sd)" == "" ]; then echo "Please, plug your USB drive in to your Keenetic device, then press 'Enter'."; read userInput; else break; fi
done
 
echo; echo "USB drives connected to your Keenetic device are specified below:";echo
local i=0
local dl
for dl in a b c d e f g h i j k l m n o p q r s t u v w x y z
do
if [ "$(fdisk -l | grep -o "/dev/sd$dl:")" == "/dev/sd$dl:" ]
then let i=$i+1; echo -n "$i. "; fdisk -l | grep "/dev/sd$dl"; echo
else return
fi
done
}

install_tools() {
local i
opkg update
i=$(opkg install fdisk)
i=$(opkg install e2fsprogs)
}

remove_tools() {
local i
i=$(opkg remove fdisk)
i=$(opkg remove e2fsprogs)
}

wait_mount() {
echo "Please wait.."
while true
do
if [ "$(ls /tmp/mnt | grep -x "$partLabel")" == "$partLabel" ]; then return; else sleep 1; fi
done
}


#---------- Main ----------
echo; echo "This script will format your USB drive to ext4 file system. "; echo "Primary partition of all disk size will be created. "; echo "All the data on the drive will be lost."; echo -n "Continue? <y/n> "
read userInput; if [ "$userInput" != "y" ]; then exit; fi
echo; echo "Searching for USB drives, please wait.."
install_tools
show_disks
select_disk

echo; echo -n "Input the desired partition label: "; read partLabel
echo "Partition '$partLabel' will be created on the drive '$diskSelect'."

echo; echo "Ready to start formatting the drive."; echo -n "WARNING! All the data on the drive '$diskSelect' will be removed! Continue? <y/n> "; read userInput
if [ "$userInput" != "y" ]; then exit; fi

echo; echo "Formating $diskSelect, please wait.."
umount_disk
make_table
make_part
format_part
wait_mount
echo; fdisk -l | grep "$diskSelect"
remove_tools
