#!/bin/bash
#-----------------------------------------------------------------------------
#
#   \brief   PrepareFlashDrive()
#
#   Function prepares USB flash drive for update
#
#   \param[in]     none
#   \param[out]    none
#   \param[in,out] none
#
#   \return
#   possible return value(s) and description
#   return 0 -> C_NO_ERROR
#   return 1 -> C_UNKOWN_ERROR
#
#   \created    05.09.2013  STW/A.Appelt
#
#-----------------------------------------------------------------------------

function PrepareFlashDrive()
{

   # connect to USB flash drive
   ConnectFlashDrive
   ret_val=$?

   if [ "$ret_val" != 0 ]; then
      echo -e "\nError: Timeout!"
      echo -e "Unable to find USB flash drive\n"
      return 1
   fi

   # copy FIT image to flash drive
   OUTPUT=`cp $VarTftpFolder/$VarImageName $flash_drive/$VarImageName`

   # wait for process to end
   wait $!

   # needed to automatically remove flash drive
   sleep 2

   sync
   # wait for process to end
   wait $!

   # get device name
   device_name=`mount | grep $flash_drive | awk -F" " '{print $1}'`

   # eject flash drive from PC
   OUTPUT=`udisks --unmount $device_name`

   # check if flash drive is unmounted
   tmp_input=$( lsblk | grep media )
   ret_val=$?
   if [ "$ret_val" == "0" ];
   then
      echo -e "\033[32mPlease safely eject USB flash drive first.\n\033[37m"
   fi

   # wait for process to end
   wait $!

   echo -e "\033[32mPlease remove USB flash drive from PC,\033[37m"
   echo -e "\033[32mconnect it to the $VarTargetName and then...\033[37m"

return 0
}


# function that connects to USB flash drive
function ConnectFlashDrive()
{
   StartTime=$(date +%s)
   SecondsLeft=$VarTimeoutConnectUsb
   while : ; do
      tmp_input=$( lsblk | grep media )
      ret_val=$?
      CurrTime=$(date +%s)
      TimeDiff=$(( $CurrTime - $StartTime ))
      if [ $TimeDiff -ge $VarTimeoutConnectUsb ]; then
         return 1
      elif [ "$ret_val" == "0" ]; then
         break
      fi
      # calculate seconds till timeout
      SecondsLeft=$(($SecondsLeft - 1))
      echo -e -n "\033[32mUSB flash drive is NOT connected. Please connect now. Timeout in $SecondsLeft s.\r\033[37m"
      sleep 1
   done

   # find index of '/media/'
   index=$(grep -o -b "/media/" <<< "$tmp_input" | cut -c1-2 )
   ((index++))

   # get name of flash drive
   flash_drive=$(expr substr "$tmp_input" "$index" 80)

   echo -e "\nUSB flash drive is connected\n"

return 0
}
