#!/usr/bin/env bash

CreatePartition="False"
WriteBootLoaders="False"

printf "device: "
read device
if [ ! -e "${device}" ]; then
    echo "Please reconfirm typos, device ${device} doesn't exist."
    exit
fi

echo "Are you want to create new FAT partition? [Yy]/[Nn]: "
while :
do
    read YesNo
    case "${YesNo}" in
      [Nn] ) break ;;
      [Yy] ) CreatePartition="True"; break ;;
      * ) echo "You must enter \"Y\", \"y\", \"N\" or \"n\"." ;;
    esac
done
YesNo=""

echo "Are you want to write boot loaders? [Yy]/[Nn]: "
while :
do
    read YesNo
    case "${YesNo}" in
      [Nn] ) break ;;
      [Yy] ) WriteBootLoaders="True"; break ;;
      * ) echo "You must enter \"Y\", \"y\", \"N\" or \"n\"." ;;
    esac
done
YesNo=""

printf "Please enter sudo password: "
read password

echo ""
echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
echo "!!!! CAUTION !!!!!!!! CAUTION !!!!!!!! CAUTION !!!!"
echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
echo ""
echo "All contents of the device ${device} are deleted or overwritten."
echo "Are you sure you want to proceed? [Yy]/[Nn]: "
while :
do
    read YesNo
    case "${YesNo}" in
      [Nn] ) echo "Cancelled by user's operation."; exit ;;
      [Yy] ) echo "Continued by user's operation."; break ;;
      * ) echo "You must enter \"Y\", \"y\", \"N\" or \"n\"." ;;
    esac
done

if [ "${CreatePartition}" == "True" ]; then
    (echo "${password}" | sudo -S echo "" ; umount ${device}1 ; echo "d
d
d
d
n
p
1



t
c
w
" | sudo fdisk ${device} ; sudo mkfs.vfat ${device}1)
fi

if [ "${WriteBootLoaders}" == "True" ]; then
    (cd output/images/ ; echo "${password}" | sudo -S dd if=SPL of=${device} bs=512 seek=2 oflag=dsync)
    (cd output/images/ ; echo "${password}" | sudo -S dd if=u-boot.img of=${device} bs=512 seek=138 oflag=dsync)
fi

echo "Please copy boot script, zImage, rootfs and device tree files to SD card."
echo "cp -ra output/images/SD_contents/boot/ /media/${USER}/<YourSDCardLabel>/"

