#!/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() 
{
   if [ "$1" == "forPC" ];
   then
     
      # 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 $!

   elif [ "$1" == "forTC3" ]; 
   then

      sync
      # wait for process to end   
      wait $!
      
      # eject flash drive from PC
      OUTPUT=`udisks --unmount /dev/sdb1`
      OUTPUT=`udisks --detach /dev/sdb`
  
      # 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 TC3 and restart the TC3.\033[37m"  

      # start buffering RS232 traffic
      cat $serial_port > "$script_dir/$VarTmpFile" &
      sleep 0.1   

   else
      return 1
   fi

return 0
}


# function that connects to USB flash drive
function ConnectFlashDrive() 
{
   StartTime=$(date +%s)
   SecondsLeft=$VarTimeoutConnectUsb
   while true;
   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
}
