#!/bin/bash
#-----------------------------------------------------------------------------
#
#   \brief   CheckUpdateSuccess()
#
#   Function checks if updating was successful.
#
#   \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    30.08.2013  STW/A.Appelt
#
#-----------------------------------------------------------------------------

function CheckUpdateSuccess() 
{

   if (! waitForString "Have a lot of fun...")
   then
      echo "+++++++++++++++++++++++++++++++++++++++++"
      echo -e "\nUpdate was not successful."
      return 1
   else
      echo "+++++++++++++++++++++++++++++++++++++++++"
   fi  

   # read in: $VarTmpFile
   tmp_input=$( grep -o "Update data loaded" "$script_dir/$VarTmpFile" )   
   
   if [ -z "$tmp_input" ]
   then
      echo -e "\nUpdate was not successful."
      return 1   
   fi 

   echo -e "\nTC3 is started.\n"

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

   # login as root
   echo "root" > $serial_port   

   # wait for TC3 promt
   if (! waitForPromt "#")
   then
      echo -e "\nError: Timeout!"
      echo -e "Unable to find TC3 promt.\n"
      return 1
   fi 

   echo -e "You are logged in the TC3.\n"  

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

   # read out eeprom status variable
   echo "stw_eep -r udstat" > $serial_port

   # wait for TC3 promt
   if (! waitForPromt "#")
   then
      echo -e "\nError: Timeout!"
      echo -e "Unable to find TC3 promt.\n"
      return 1
   fi

   # check if status = success
   if ( ! grep -o "SUCCESS:" "$script_dir/$VarTmpFile"); 
   then   
      echo -e "Error: Update was not successful."
      return 1  
   fi
   
   echo -e "Update was successful.\n"   

return 0
}

# function to search for a string
function waitForString() 
{
#   StartTime=$(date +%s)
   tail -f "$script_dir/$VarTmpFile" | 
   while read line; do
#      CurrTime=$(date +%s)
#      TimeDiff=$(( $CurrTime - $StartTime ))
#      if [ $TimeDiff -ge 50 ]; 
#      then
#         killall tail
#         return 1
      if test "${line#*"$1"}" != "$line"
      then
         echo "$line"    
         killall tail 
         return 0
      else
         echo "$line"
      fi
   done 
   OUT=$? 
#   CurrTime=$(date +%s)
#   TimeDiff=$(( $CurrTime - $StartTime ))
   if [ "$OUT" == 0 ]; then #-a $TimeDiff -le 50 ]; then
      killall cat
      return 0
   fi
   killall cat
return 1
}

