#!/bin/bash
#-----------------------------------------------------------------------------
#
#   \brief   PreparenNandFlash()
#
#   Function prepares NAND flash.
#
#   \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    02.09.2013  STW/A.Appelt
#
#-----------------------------------------------------------------------------

function PrepareNandFlash() 
{
   filename="$script_dir/$VarTmpFile"

   # start buffering RS232 traffic
   OUTPUT=`cat $serial_port > "$script_dir/$VarTmpFile" &`
   sleep 0.1   
   
   # check if mounted
   echo "nand_ismounted.sh" > $serial_port

   # wait for TC3 promt
   if (! waitForPromt "#")
   then
      echo -e "\nError: Timeout!"
      echo -e "Unable to find TC3 promt.\n"
      return 1
   fi 
   
   # read in: $VarTmpFile
   tmp_input=$( grep -o "NAND flash mounted" "$filename" ) 

   if [ ! -z "$tmp_input" ]
   then
      echo -e "Unmount NAND flash...\n"
      echo "nand_umount.sh" > $serial_port    
   fi

   echo -e "NAND flash is not mounted\n"

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

   # prepare NAND flash
   echo "nand_prepare.sh" > $serial_port

   if (! waitForPromt "CAUTION:") 
   then
      echo -e "\Could not prepare NAND flash."
      return 1
   fi  
   
   echo -e "Preparing NAND flash...\n"

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

   # acknowledge 
   echo "Y" > $serial_port

   if (! waitForNandFlash "#")
   then
      echo -e "\nError: Could not find TC3 prompt."
      return 1
   fi  

   echo -e "NAND flash is prepared.\n"

return 0
}


# function to search for a string
function waitForNandFlash() 
{
   StartTime=$(date +%s)
   while true;
   do
      CurrTime=$(date +%s)
      TimeDiff=$(( $CurrTime - $StartTime ))
      line=$(tail -1 "$script_dir/$VarTmpFile")       
      if [ $TimeDiff -ge 300 ]; 
      then
         killall tail
         return 1
      elif test "${line#*"$1"}" != "$line"
      then
         echo "$line" 
         killall cat
         return 0
      fi
   done 
   killall cat
return 1
}  
