#!/bin/bash
#-----------------------------------------------------------------------------
#
#   \brief   SetUBootEnvVar()
#
#   Function sets the environmental variables in the UBoot.
#
#   \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     29.08.2013  STW/A.Appelt
#
#-----------------------------------------------------------------------------

function SetUBootEnvVar() 
{
   # start buffering RS232 traffic
   cat $serial_port > "$script_dir/$VarTmpFile" &
   sleep 0.1     

   # Check if VarTftpDownload == true
   if [ "$1" == true ];
   then  
      # set env. variables for update via tftp
      echo "setenv gatewayip $VarGatewayIP" > $serial_port
      sleep 0.1
      echo "setenv ipaddr $VarClientIP" > $serial_port
      sleep 0.1
      echo "setenv netmask $VarNetMask" > $serial_port
      sleep 0.1
      echo "setenv serverip $VarServerIP" > $serial_port
      sleep 0.1
      
      echo "setenv update_en_tftp 1" > $serial_port
      sleep 0.1
      echo "setenv update_en_usb 0" > $serial_port
      sleep 0.1

   else
      # set env. variables for update via USB
      echo "setenv update_en_tftp 0" > $serial_port
      sleep 0.1
      echo "setenv update_en_usb 1" > $serial_port
      sleep 0.1
   fi

   echo "setenv update_file image.fit" > $serial_port
   sleep 0.1
   echo "setenv update_pswd skywalker" > $serial_port
   sleep 0.1

   # Check if VarRootFileSystemStatus == true
   if [ "$2" == true ]; 
   then
      # set Rootfs Read/Write
      echo "setenv net_ubifs_args setenv bootargs console=ttyPSC3,115200 ubi.mtd=0 root=ubi0:rootfs rw rootfstype=ubifs quiet" > $serial_port
   else
      # set Rootfs Read only
      echo "setenv net_ubifs_args setenv bootargs console=ttyPSC3,115200 ubi.mtd=0 root=ubi0:rootfs ro rootfstype=ubifs quiet" > $serial_port
   fi

   # wait for UBoot promt (this function can be found in the 'EnterUBoot' script)
   if (! waitForPromt "=>")
   then
      echo -e "\nError: Timeout!"
      echo -e "Unable to find UBoot promt.\n"
      return 1
   fi  

   echo -e "UBoot variables are set for update via TFTP.\n"

   # start buffering RS232 traffic
   cat $serial_port > "$script_dir/$VarTmpFile" & 
   sleep 0.1      
   
   # save env. variables
   echo "saveenv" > $serial_port

   # wait for UBoot promt (this function can be found in the 'EnterUBoot' script)
   if (! waitForPromt "=>")
   then
      echo -e "\nError: Timeout!"
      echo -e "Unable to find UBoot promt.\n"
      return 1
   fi
   
   # Check if VarTftpDownload == true
   if [ "$1" == true ];
   then 
      echo -e "UBoot variables are saved.\n"

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

      # perform reset
      echo -e "Performing update...\n"
      echo "reset" > $serial_port
   fi

return 0
}
