#!/bin/bash
#-----------------------------------------------------------------------------
#
#   \brief   ReadConfigFile()
#
#   This function reads the user parameter out of the config.ttl file.
#
#   \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 ReadConfigFile()
{
   # Read User Settings from Config File

   filename="$script_dir/$VarConfigFile"
   activated=" = 1"
   ip_structure="[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}"

   # Check if config.ttl file exists
   if [ ! -s "$filename" ]; then
      echo -e "$VarConfigFile file does not exist!"
      return 1
   fi

   # read in: VarRootFileSystemStatus
   if (! ReadVariable "VarRootFileSystemStatus" $filename ); then
      VarRootFileSystemStatus=false
   else
      VarRootFileSystemStatus=true
   fi

   # check if VarOverlayStatus exists
   if ( ! grep "VarOverlayStatus" $filename &>/dev/null ); then
      # add overlay variable to config.ttl file
      sed -i '/VarPrepareNandFlash/a\                                ; 1.. overlay (unionfs) is acitvated'    $filename
      sed -i '/VarPrepareNandFlash/a VarOverlayStatus          = 0   ; 0.. overlay (unionfs) is deactivated,' $filename
      sed -i '/VarPrepareNandFlash/a\ ' $filename
      VarOverlayStatus=false
   else
      # read in: VarOverlayStatus
      if (! ReadVariable "VarOverlayStatus" $filename ); then
         VarOverlayStatus=false
      else
         VarOverlayStatus=true
      fi
   fi

   # read in: VarComponentUboot
   if (! ReadVariable "VarComponentUboot" $filename ); then
      VarComponentUboot=false
   else
      VarComponentUboot=true
   fi

   # read in: VarComponentUbootEnvVars
   if (! ReadVariable "VarComponentUbootEnvVars " $filename ); then
      VarComponentUbootEnvVars=false
   else
      VarComponentUbootEnvVars=true
   fi

   # read in: VarMachinesCloudService
   if (! ReadVariable "VarMachinesCloudService " $filename ); then
      VarMachinesCloudService=false
   else
      VarMachinesCloudService=true
   fi
   # APP: deactivated functionality
   VarMachinesCloudService=false

   # read in: VarComponentKernel
   if (! ReadVariable "VarComponentKernel" $filename ); then
      VarComponentKernel=false
   else
      VarComponentKernel=true
   fi

   # read in: VarComponentFdt
   if (! ReadVariable "VarComponentFdt" $filename ); then
      VarComponentFdt=false
   else
      VarComponentFdt=true
   fi

   # read in: VarComponentRootfs
   if (! ReadVariable "VarComponentRootfs" $filename ); then
      VarComponentRootfs=false
   else
      VarComponentRootfs=true
   fi

   # read in: VarPrepareNandFlash
   if (! ReadVariable "VarPrepareNandFlash" $filename ); then
      VarPrepareNandFlash=false
   else
      VarPrepareNandFlash=true
   fi

   # read in: VarUpdateUBootPasswd
   if (! ReadVariable "VarUpdateUBootPasswd" $filename ); then
      VarUpdateUBootPasswd="do nothing"
      VarUpdatePassword="false"
      VarNoUpdatePassword="true"
   else
      VarUpdateUBootPasswd="set password"
      VarUpdatePassword="true"
      VarNoUpdatePassword="false"
   fi

   # # read in: VarTftpDownload
   # if (! ReadVariable "VarTftpDownload" $filename ); then
   #    VarTftpDownload=false
   # else
   #    VarTftpDownload=true
   # fi

   # force tftp download, usb is not supported
   VarTftpDownload=true

   if [ "$VarTftpDownload" == true -o "$VarUpdateNow" == false ]; then
      # read in: VarServerIP
      ReadIPAddress "VarServerIP" $filename
      if [ "$ret_ip" != false ]; then
         VarServerIP=$ret_ip
      else
         echo -e "Could not read server IP address from config file."
         VarServerIP="enter value"
         if ( "$VarUpdateNow" ); then
            return 1
         fi
      fi

      # read in: VarClientIP
      ReadIPAddress "VarClientIP" $filename
      if [ "$ret_ip" != false ]; then
         VarClientIP=$ret_ip
      else
         echo -e "Could not read client IP address from config file."
         VarClientIP="enter value"
         if ( "$VarUpdateNow" ); then
            return 1
         fi
      fi
      # read in: VarNetMask
      ReadIPAddress "VarNetMask" $filename

      if [ "$ret_ip" != false ]; then
         VarNetMask=$ret_ip
      else
         echo -e "Could not read net mask from config file."
         VarNetMask="enter value"
         if ( "$VarUpdateNow" ); then
            return 1
         fi
      fi
      # read in: VarGatewayIP
      ReadIPAddress "VarGatewayIP" $filename

      if [ "$ret_ip" != false ]; then
         VarGatewayIP=$ret_ip
      else
         echo -e "Could not read gateway IP address from config file."
         VarGatewayIP="can stay empty"
      fi
   fi

   # Read System Setting from Config File

   # read in: serial_port
   ReadSystemVariable "VarSerialPort" $filename
   if [ "$ret_var" != false ]; then
      serial_port=$ret_var
   else
      serial_port="/dev/ttyS0"
      echo -e "Could not read serial_port, using /dev/ttyS0 as default path."
   fi

   # read in: VarFileNameRootfs
   ReadSystemVariable "VarFileNameRootfs" $filename
   if [ "$ret_var" != false ]; then
      VarFileNameRootfs=$ret_var
   else
      echo -e "Could not read system variable \"VarFileNameRootfs\" from config file."
      return 1
   fi

   # read in: VarFileNameKernel
   ReadSystemVariable "VarFileNameKernel" $filename
   if [ "$ret_var" != false ]; then
      VarFileNameKernel=$ret_var
   else
      echo -e "Could not read system variable \"VarFileNameKernel\" from config file."
      return 1
   fi

   # read in: VarFileNameFdt
   ReadSystemVariable "VarFileNameFdt" $filename
   if [ "$ret_var" != false ]; then
      VarFileNameFdt=$ret_var
   else
      echo -e "Could not read system variable \"VarFileNameFdt\" from config file."
      return 1
   fi

   # read in: VarFileNameUboot
   ReadSystemVariable "VarFileNameUboot" $filename
   if [ "$ret_var" != false ]; then
      VarFileNameUboot=$ret_var
   else
      echo -e "Could not read system variable \"VarFileNameUboot\" from config file."
      return 1
   fi

   # read in: VarFileNameUbootEnv
   ReadSystemVariable "VarFileNameUbootEnv" $filename
   if [ "$ret_var" != false ]; then
      VarFileNameUbootEnv=$ret_var
   else
      echo -e "Could not read system variable \"VarFileNameUbootEnv\" from config file."
      return 1
   fi

   # read in: VarUbootAddress
   ReadSystemVariable "VarFlashAddrUbootStart2012_10" $filename
   if [ "$ret_var" != false ]; then
      VarUbootAddress="0x$ret_var"
   else
      echo -e "Could not read system variable \"VarFlashAddrUbootStart2012_10\" from config file."
      return 1
   fi

   # read in: VarKernelAddress
   ReadSystemVariable "VarFlashAddrKernelStart" $filename
   if [ "$ret_var" != false ]; then
      VarKernelAddress="0x$ret_var"
   else
      echo -e "Could not read system variable \"VarFlashAddrKernelStart\" from config file."
      return 1
   fi

   # read in: VarRootfsAddress
   ReadSystemVariable "VarFlashAddrRootfsStart" $filename
   if [ "$ret_var" != false ]; then
      VarRootfsAddress="0x$ret_var"
   else
      echo -e "Could not read system variable \"VarFlashAddrRootfsStart\" from config file."
      return 1
   fi

   # read in: VarFdtAddress
   ReadSystemVariable "VarFlashAddrFdtStart2012_10" $filename
   if [ "$ret_var" != false ]; then
      VarFdtAddress="0x$ret_var"
   else
      echo -e "Could not read system variable \"VarFlashAddrFdtStart2012_10\" from config file."
      return 1
   fi

   # rootfs status
   if [ "$VarRootFileSystemStatus" == true ]; then
      rootfs_status="read / write"
      VarRootfsReadWrite=true
      VarRootfsReadOnly=false
   else
      rootfs_status="read only"
      VarRootfsReadWrite=false
      VarRootfsReadOnly=true
   fi

   # overlay status
   if [ "$VarOverlayStatus" == true ]; then
      overlay_status="activated"
      VarOverlayOn=true
      VarOverlayOff=false
   else
      overlay_status="deactivated"
      VarOverlayOff=true
      VarOverlayOn=false
   fi

   # tftp status
   if [ "$VarTftpDownload" == true ]; then
      tftp_status="tftp"
      VarUpdateViaTftp=true
      VarUpdateViaUSB=false
   else
      tftp_status="usb"
      VarUpdateViaTftp=false
      VarUpdateViaUSB=true
   fi

   if [ "$VarUpdateNow" == false ]; then
      # Read User Config
      ReadUserConfig
      if [ "$?" == "1" ]; then
         return 1
      fi
      # save values to config file
      SaveValuesToConfigFile
   else
      if [ "$VarUpdateUBootPasswd" == "set password" ]; then
         # Read Password without GUI
         echo -e "\nLeave empty for removing the password"
         echo -e "Type 'none' for not touching the password"
         echo -n "Set UBoot password: "
         read -s VarNewUBootPassword
         if [ "$VarNewUBootPassword" == "none" ]; then
            VarNewUBootPassword="none"
            echo -e "\n\033[40;32mUBoot Password will not be touched\033[0m\n"
            sleep 2
         else
            # confirm password
            echo ""
            echo -n "Confirm UBoot password: "
            read -s VarNewUBootPasswordConfirm

            if [[ "$VarNewUBootPassword" == "$VarNewUBootPasswordConfirm" ]]; then
               if [[ "$VarNewUBootPassword" == "" ]]; then
                  echo -e "\n\033[40;32mUBoot Password will be removed\033[0m\n"
                  sleep 2
               else
                  echo -e "\n\033[40;32mNew UBoot Password will be set\033[0m\n"
                  sleep 2
               fi
            else
               echo -e "\n\033[31mWrong entry!\nPasswords did not match!\033[37m\n"
               sleep 2
               exit 1
            fi
         fi
         VarUpdatePassword="true"
         VarNoUpdatePassword="false"
      else

         VarUpdateUBootPasswd="do nothing"
         VarUpdatePassword="false"
         VarNoUpdatePassword="true"
      fi
   fi

   #check if user is in the dialout group
   user=$(whoami)
   cat /etc/group | grep "dialout" | grep -q "$user"
   if [ "$?" == "1" ] && [ "$user" != "root" ]; then
      if [ ! -w "$serial_port" ] || [ ! -r "$serial_port" ]; then
         `echo -e "$PASSW\n" | sudo -S chmod -R 666 $serial_port`
         sleep 0.5
      fi
   fi

   echo -e "\n********************************** General Information ******************************"
   echo -e ""
   echo -e "User             = `whoami`"
   echo -e "Hostname         = `hostname`"
   echo -e "Operation System = `cat /etc/lsb-release | grep DISTRIB_DESCRIPTION  | awk -F'"' '{print $2}' | awk -F'"' '{print $1}' `"
   echo -e "Updater Version  = $VarVersionNumber"
   echo -e ""
   echo -e "*************************************************************************************\n"

   echo -e "\n*********************** User Configurations for Linux Updater ***********************"
   echo -e ""
   echo -e "General Settings:"
   echo -e "Serial Port          = $serial_port"
   echo -e "Log-File             = $VarLogFilePath"
   echo -e "Data-Folder          = $VarDataFolderPath"
   echo -e "Set/Update Uboot Pwd = $VarUpdateUBootPasswd"
   echo -e ""
   echo -e "Root File System Settings:"
   echo -e "VarRootFileSystemStatus = $VarRootFileSystemStatus\t; TRUE  -> root file system is read write"
   echo -e "\t\t\t\t; FALSE -> root file system will be set to read only"
   echo -e "VarOverlayStatus \t= $VarOverlayStatus\t; FALSE -> overlay (unionfs) is deactivated"
   echo -e "\t\t\t\t; TRUE  -> overlay (unionfs) is activated"
   echo -e ""
   echo -e "Components to be installed:"
   echo -e "VarComponentUboot       = $VarComponentUboot\t; install uboot"
   echo -e "VarComponentKernel      = $VarComponentKernel\t; install kernel"
   echo -e "VarComponentFdt         = $VarComponentFdt\t; install flattened device tree"
   echo -e "VarComponentRootfs      = $VarComponentRootfs\t; install root file system"
   echo -e "VarPrepareNandFlash     = $VarPrepareNandFlash\t; prepare (format) the NAND data flash"
   echo -e "VarComponentUbootEnvVars= $VarComponentUbootEnvVars\t; update uboot enviroment variables"
#APP echo -e "VarMachinesCloudService = $VarMachinesCloudService\t; activate machines.cloud service"
   echo -e ""
   echo -e "Update mode:"
   echo -e "VarTftpDownload         = $VarTftpDownload\t; TRUE  -> enables update via TFTP Download"
   echo -e "\t\t\t\t; FALSE -> enables update via USB"
   if ( "$VarTftpDownload" ); then
      echo -e ""
      echo -e "Network settings for TFTP data download:"
      echo -e "VarServerIP             = $VarServerIP \t; TFTP server ip (ip of host PC)"
      echo -e "VarClientIP             = $VarClientIP \t; ip of $VarTargetName"
      echo -e "VarNetMask              = $VarNetMask \t; network mask"
      echo -e "VarGatewayIP            = $VarGatewayIP \t; gateway ip"
      echo -e ""
   fi
   echo -e "*************************************************************************************\n"

return 0
}

##################################### functions ###################################

# Read User Config
ReadUserConfig()
{
   while :; do
if ( "$VarTftpDownload" ); then
text="Current Updater Configuration: \
\nUpdate Method: \t <b>via $tftp_status</b>  \
\n\t<i> Host IP: \t\t $VarServerIP  </i>\
\n\t<i> Client IP: \t\t $VarClientIP </i>\
\n\t<i> Net Mask: \t $VarNetMask </i>\
\n\t<i> Gateway IP: \t $VarGatewayIP </i>\
\nRootFS Status: \t <b>$rootfs_status</b>  \
\nOverlay Status:\t <b>$overlay_status</b>  \
\nSerial Port: \t\t <b>$serial_port</b>  \
\nUBoot Password:\t <b>$VarUpdateUBootPasswd</b> \
\nTo change the above configuration press \"Configure\". \
\n \
\nThe list below shows the components that needs to be  \
\nupdated. To update a \ component it needs to be selected. \
\nTo start the update procedure press \"Start update\" "
#APP height=520
height=495
else
text="Current Updater Configuration: \
\nUpdate Method: \t <b>via $tftp_status</b>  \
\nRootFS Status: \t <b>$rootfs_status</b>  \
\nOverlay Status:\t <b>$overlay_status</b>  \
\nSerial Port: \t\t <b>$serial_port</b>  \
\nUBoot Password:\t <b>$VarUpdateUBootPasswd</b> \
\nTo change the above configuration press \"Configure\". \
\n \
\nThe list below shows the components that needs to be  \
\nupdated. To update a \ component it needs to be selected. \
\nTo start the update procedure press \"Start update\" "
#APP height=450
height=425
fi
      # read config values from user
      option=$(zenity --list --checklist \
             --height "$height" --width 250 \
             --title "$VarTargetName Updater" \
             --text "$text" \
             --column "select" --column "component" \
             --ok-label="Start update" \
             --cancel-label="Configure" \
             $VarComponentUboot "update Uboot" \
             $VarComponentUbootEnvVars "update Environment Variables" \
             $VarComponentKernel "update Kernel" \
             $VarComponentFdt "update Flatened Device Tree" \
             $VarComponentRootfs "update Root File System" \
             $VarPrepareNandFlash "prepare NAND Flash")
             #APP $VarMachinesCloudService "activate machines.cloud Service")
      ret_val="$?"


if ( "$VarTftpDownload" ); then
text="Select option(s) and press \"Continue\" \n \
\nUpdate Method: \t <b>via $tftp_status</b>  \
\n\t<i> Host IP: \t\t $VarServerIP  </i>\
\n\t<i> Client IP: \t\t $VarClientIP </i>\
\n\t<i> Net Mask: \t $VarNetMask </i>\
\n\t<i> Gateway IP: \t $VarGatewayIP </i>\
\nRootFS Status: \t <b>$rootfs_status</b>  \
\nOverlay Status:\t <b>$overlay_status</b>  \
\nSerial Port: \t\t <b>$serial_port</b> \
\nUBoot Password:\t <b>$VarUpdateUBootPasswd</b>"
height=410
else
text="Select option(s) and press \"Continue\" \n \
\nUpdate Method: \t <b>via $tftp_status</b>  \
\nRootFS Status: \t <b>$rootfs_status</b>  \
\nOverlay Status:\t <b>$overlay_status</b>  \
\nSerial Port: \t\t <b>$serial_port</b> \
\nUBoot Password:\t <b>$VarUpdateUBootPasswd</b>"
height=340
fi

      # check return value
      if [ "$ret_val" == "1" ]; then
         # read the options selected by the user
         option=$(zenity --list --checklist \
                         --title "$VarTargetName Updater" \
                         --height $height --width 295 \
                         --text "$text" \
                         --column "select" --column "option" \
                         --ok-label=Continue \
                         --cancel-label="Exit updater" \
                         FALSE "change Update Method" \
                         FALSE "change RootFS Status" \
                         FALSE "change Overlay Status" \
                         FALSE "change Serial Port" \
                         FALSE "change UBoot Password Status" )

         # check return value
         if [ "$?" != "0" ]; then
            exit
         fi

         # change update methode
         if echo "$option" | grep -q "Method"; then
            # configure update method
            configureTFTP
         fi

         # set / update uboot password
         if echo "$option" | grep -q "Password"; then

            OUTPUT=$(zenity --height=160 --width 280 --list --radiolist \
               --title "$VarTargetName Updater" \
               --text 'Select UBoot password:' \
               --column 'select' --column 'status' \
               $VarUpdatePassword "set or remove password" $VarNoUpdatePassword "do nothing")

            # check return value
            if [ "$?" == "0" ]; then
               if echo "$OUTPUT" | grep -q "set"; then
                  # get passwd via GUI
                  VarNewUBootPassword=$(zenity --entry --hide-text \
                     --cancel-label="Cancel" \
                     --ok-label="Set" \
                     --text "Set UBoot password:\n(leave empty for removing the password)" \
                     --title "$VarTargetName Updater")

                  # Check for cancellation.
                  if [[ ${?} != 0 ]]; then
                     VarNewUBootPassword="none"
                  else
                     # get passwd via GUI
                     VarNewUBootPasswordConfirm=$(zenity --entry --hide-text \
                        --cancel-label="Cancel" \
                        --ok-label="Confirm" \
                        --text "Confirm UBoot password:" \
                        --title "$VarTargetName Updater")

                     if [[ "$VarNewUBootPassword" == "$VarNewUBootPasswordConfirm" ]]; then
                        if [[ "$VarNewUBootPassword" == "" ]]; then
                           # with GUI
                           $(zenity --info \
                              --title "$VarTargetName Updater" \
                              --text "UBoot Password will be removed")
                        else
                           # with GUI
                           $(zenity --info \
                              --title "$VarTargetName Updater" \
                              --text "New UBoot Password will be set")
                        fi
                        VarUpdateUBootPasswd="set password"
                     else
                        # with GUI
                        $(zenity --error \
                           --title "$VarTargetName Updater" \
                           --text '<span color="red"><b>Wrong entry!\nPasswords did not match!</b></span>')
                        exit 1
                     fi
                  fi
                  VarUpdatePassword="true"
                  VarNoUpdatePassword="false"
               else
                  VarUpdateUBootPasswd="do nothing"
                  VarUpdatePassword="false"
                  VarNoUpdatePassword="true"
               fi
            fi
         fi

         # change rootfs status
         if echo "$option" | grep -q "RootFS Status"; then
            OUTPUT=$(zenity --height=160 --width 280 --list --radiolist \
                            --title "$VarTargetName Updater" \
                            --text 'Select Rootfs Status:' \
                            --column 'select' --column 'status' \
                            $VarRootfsReadWrite "read / write" $VarRootfsReadOnly "read only")

            # check return value
            if [ "$?" == "0" ]; then
               if echo "$OUTPUT" | grep -q "only"; then
                  # set rootfs status to read only
                  VarRootFileSystemStatus=false
                  rootfs_status="read only"
                  VarRootfsReadWrite=false
                  VarRootfsReadOnly=true
               else
                  # set rootfs status to read / write
                  rootfs_status="read / write"
                  VarRootFileSystemStatus=true
                  VarRootfsReadWrite=true
                  VarRootfsReadOnly=false
               fi
            fi
         fi

         # change overlay status
         if echo "$option" | grep -q "Overlay"; then
            OUTPUT=$(zenity --height=160 --width 280 --list --radiolist \
                            --title "$VarTargetName Updater" \
                            --text 'Select Overlay Status:' \
                            --column 'select' --column 'status' \
                            $VarOverlayOn "activate" $VarOverlayOff "deactivate")

            # check return value
            if [ "$?" == "0" ]; then
               if echo "$OUTPUT" | grep -q "deactivate"; then
                  # set overlay status to deactivate
                  overlay_status="deactivated"
                  VarOverlayStatus=false
                  VarOverlayOn=false
                  VarOverlayOff=true
               else
                  # set overlay status to activate
                  overlay_status="activated"
                  VarOverlayStatus=true
                  VarOverlayOff=false
                  VarOverlayOn=true
               fi
            fi
         fi

         # select new serial port
         if echo "$option" | grep -q "Serial"; then
            OUTPUT=`ls /dev/ | egrep "ttyS|ttyUSB" | zenity --list --column="Serial Port (Cancel = default settings)" \
                                                            --title "TC3G Updater" 2>/dev/null`
            # check if a file was selected
            if [ "$?" == "0" ]; then
               serial_port="/dev/$OUTPUT"
            fi
         fi
      else
         # update component information
         ( echo "$option" | grep -q "Uboot"     ) && VarComponentUboot=true        || VarComponentUboot=false
         ( echo "$option" | grep -q "Kernel"    ) && VarComponentKernel=true       || VarComponentKernel=false
         ( echo "$option" | grep -q "Tree"      ) && VarComponentFdt=true          || VarComponentFdt=false
         ( echo "$option" | grep -q "Root"      ) && VarComponentRootfs=true       || VarComponentRootfs=false
         ( echo "$option" | grep -q "NAND"      ) && VarPrepareNandFlash=true      || VarPrepareNandFlash=false
         #APP ( echo "$option" | grep -q "machines"  ) && VarMachinesCloudService=true  || VarMachinesCloudService=false
         ( echo "$option" | grep -q "Variables" ) && VarComponentUbootEnvVars=true || VarComponentUbootEnvVars=false

         # check if tftp settings are valid
         if ( "$VarTftpDownload" ); then
            if [ "$VarServerIP" == "enter value" -o "$VarNetMask" == "enter value"  -o "$VarClientIP" == "enter value" ]; then
               # check if component is selected
               if [ "$VarComponentUboot"        == true -o "$VarComponentKernel"  == true -o \
                    "$VarComponentRootfs"       == true -o "$VarComponentFdt"     == true -o \
                    "$VarComponentUbootEnvVars" == true ]; then
                  configureTFTP
               fi
            fi
         fi

         # check if password is set if specified
         if [ "$VarUpdateUBootPasswd" == "set password" -a "$VarNewUBootPassword" == "none" ]; then
            # get passwd via GUI
            VarNewUBootPassword=$(zenity --entry --hide-text \
               --cancel-label="Cancel" \
               --ok-label="Set" \
               --text "Set UBoot password:\n(leave empty for removing the password)" \
               --title "$VarTargetName Updater")

            # Check for cancellation.
            if [[ ${?} != 0 ]]; then
               VarNewUBootPassword="none"
               # with GUI
               $(zenity --info \
                  --title "$VarTargetName Updater" \
                  --text "UBoot Password will not be touched")
            else
               # get passwd via GUI
               VarNewUBootPasswordConfirm=$(zenity --entry --hide-text \
                  --cancel-label="Cancel" \
                  --ok-label="Confirm" \
                  --text "Confirm UBoot password:" \
                  --title "$VarTargetName Updater")

               if [[ "$VarNewUBootPassword" == "$VarNewUBootPasswordConfirm" ]]; then
                  if [[ "$VarNewUBootPassword" == "" ]]; then
                     # with GUI
                     $(zenity --info \
                        --title "$VarTargetName Updater" \
                        --text "UBoot Password will be removed")
                  else
                     # with GUI
                     $(zenity --info \
                        --title "$VarTargetName Updater" \
                        --text "New UBoot Password will be set")
                  fi
               else
                  # with GUI
                  $(zenity --error \
                     --title "$VarTargetName Updater" \
                     --text '<span color="red"><b>Wrong entry!\nPasswords did not match!</b></span>')
                  exit 1
               fi
            fi
         fi

         # at least one component needs to be selected
         if [ "$VarComponentUboot"        == false -a "$VarComponentKernel"  == false -a \
              "$VarComponentRootfs"       == false -a "$VarComponentFdt"     == false -a \
              "$VarComponentUbootEnvVars" == false -a "$VarPrepareNandFlash" == false -a \
              "$VarUpdateUBootPasswd" == false ]; then
              #APP "$VarMachinesCloudService"  == false -a "$VarUpdateUBootPasswd" == false ]; then
            # print error message
            $(zenity --error --title "$VarTargetName Updater - Error" --text="No component selected!")
         else
            # start update procedure
            break
         fi
      fi
   done
}

# read user config tftp
configureTFTP()
{
   # select between usb and tftp
   OUTPUT=$(zenity --height=160 --width 280 --list --radiolist \
                   --ok-label="Continue" \
                   --cancel-label="Exit updater" \
                   --title "$VarTargetName Updater" \
                   --text 'Select Update Methode:' \
                   --column 'select' --column 'methode' \
		   $VarUpdateViaTftp "update via TFTP" $VarUpdateViaUSB "update via USB")

   # check return value
   if [ "$?" == "0" ]; then
      if echo "$OUTPUT" | grep -q "TFTP"; then
         # read user config tftp
         while :;do
            VarTftpDownload=true
            tftp_status="tftp"
            VarUpdateViaTftp=true
            VarUpdateViaUSB=false

            # get host IP
            hostIP=`ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1'`

            # enter IP information
            OUTPUT=$(zenity --forms --separator="," \
                        --title="$VarTargetName Updater" \
                        --ok-label="Continue" \
                        --cancel-label="Exit updater" \
                        --text="TFTP Settings \n\n   Host IP: \t\t\t $hostIP \n   Client IP: \t\t\t $VarClientIP \n   Net Mask: \t\t\t $VarNetMask \n   Gateway IP: \t\t $VarGatewayIP" \
                        --add-entry="replace Client IP:" \
                        --add-entry="replace Net Mask:" \
                        --add-entry="replace Gateway IP:" )

            # check return value
            if [ "$?" == "0" ]; then
               # save IPs
               tmpClientIP=$(awk -F, '{print $1}' <<<$OUTPUT)
               tmpNetMask=$(awk -F, '{print $2}' <<<$OUTPUT)
               tmpGatewayIP=$(awk -F, '{print $3}' <<<$OUTPUT)
               VarServerIP=$hostIP
               NoError=true

               # check IPs and store if valid
               if [ -n "$tmpClientIP" ]; then
                  if grep -o -q "$ip_structure" <<< "$tmpClientIP"
                  then
                     VarClientIP=$(grep -o "$ip_structure" <<< "$tmpClientIP")
                  else
                     $(zenity --error --title "$VarTargetName Updater - Error" --text="Could not read Client IP address.")
                     NoError=false
                  fi
               fi
               if [ -n "$tmpNetMask" ]; then
                  if grep -o -q "$ip_structure" <<< "$tmpNetMask"
                  then
                     VarNetMask=$(grep -o "$ip_structure" <<< "$tmpNetMask")
                  else
                     $(zenity --error --title "$VarTargetName Updater - Error" --text="Could not read netmask.")
                     NoError=false
                  fi
               fi
               if [ -n "$tmpGatewayIP" ]; then
                  if grep -o -q "$ip_structure" <<< "$tmpGatewayIP"
                  then
                     VarGatewayIP=$(grep -o "$ip_structure" <<< "$tmpGatewayIP")
                  else
                     $(zenity --error --title "$VarTargetName Updater - Error" --text="Could not read gateway IP address.")
                     NoError=false
                  fi
               fi

               # check if error occured and exit loop
               if [ "$NoError" == true -a "$VarNetMask" != "enter value"  -a "$VarClientIP" != "enter value" ]; then
                  # exit tftp settings
                  break
               fi
            else
               exit
            fi
         done
      else
         # set variables for update via usb
         tftp_status="usb"
         VarTftpDownload=false
         VarUpdateViaTftp=false
         VarUpdateViaUSB=true
      fi
   else
      exit
   fi
return
}

# Read Value of Variable
function ReadVariable()
{
   while read line;
   do
      if test "${line#*"$1"}" != "$line"
      then
         param="$1"
         length=${#param}
         character=$(expr substr "$line" 1 "$length")

         if [ "$character" == "$1" ]; then
            # find index of '='
            index=$(grep -o -b "=" <<< "$line" | cut -c1-2 )
            if [ ! "$index" ]; then
               return 1;
            fi
            ((index++))

         while (true);
         do
            ((index++))
            # get character
            character=$(expr substr "$line" "$index" 1)
            # compare character
            if [ "$character" == " " ]; then
               : # do nothing
            elif [ "$character" == "1" ]; then
               # found '1'
               return 0
            else
               # found not '1'
               return 1
            fi
         done
         fi
      fi
   done < "$2"
}

# Read Value of Variable
function ReadSystemVariable()
{
   ret_var=false;
   while read line;
   do
      if test "${line#*"$1"}" != "$line"
      then
         param="$1"
         length=${#param}
         character=$(expr substr "$line" 1 "$length")
         if [ "$character" == "$1" ]; then
            # extract substring between "'" and "'"
            #ret_var=`echo "$line"  | sed -n -e "/=/ s|.*'\(.*\)'.*|\1|p"`
            ret_var=`echo "$line" | awk -F"'" '{print $2}' | awk -F"'" '{print $1}'`
            return 0
         fi
      fi
   done < "$2"
}

# Read IP Address
function ReadIPAddress()
{
   ret_ip=false;
   while read line;
   do
      if test "${line#*"$1"}" != "$line"
      then
         param="$1"
         length=${#param}
         character=$(expr substr "$line" 1 "$length")

         if [ "$character" == "$1" ];
         then
            if grep -o -q "$ip_structure" <<< "$line"
            then
               ret_ip=$(grep -o "$ip_structure" <<< "$line")
               return 0
            fi
         fi
      fi
   done < "$2"
}

# save values to config file
SaveValuesToConfigFile()
{
   sed -i '/VarSerialPort/c\VarSerialPort   = '"'$serial_port'"' '      $script_dir/$VarConfigFile
   sed -i '/; The serial port/c\VarSerialPort   = '"'$serial_port'"' '  $script_dir/$VarConfigFile

   ( "$VarRootFileSystemStatus"  ) && VarTmp=1 || VarTmp=0
   sed -i '/VarRootFileSystemStatus/c\VarRootFileSystemStatus   = '$VarTmp'   ; 1.. root file system is read write,' $script_dir/$VarConfigFile
   ( "$VarOverlayStatus"         ) && VarTmp=1 || VarTmp=0
   sed -i '/VarOverlayStatus/c\VarOverlayStatus          = '$VarTmp'   ; 0.. overlay (unionfs) is deactivated,'      $script_dir/$VarConfigFile
   ( "$VarComponentUbootEnvVars" ) && VarTmp=1 || VarTmp=0
   sed -i '/VarComponentUbootEnvVars/c\VarComponentUbootEnvVars  = '$VarTmp'   ; update uboot enviroment variables (is always set under windows)'  $script_dir/$VarConfigFile
   ( "$VarComponentUboot"        ) && VarTmp=1 || VarTmp=0
   sed -i '/VarComponentUboot /c\VarComponentUboot         = '$VarTmp'   ; install uboot'                            $script_dir/$VarConfigFile
   ( "$VarComponentKernel"       ) && VarTmp=1 || VarTmp=0
   sed -i '/VarComponentKernel/c\VarComponentKernel        = '$VarTmp'   ; install kernel'                           $script_dir/$VarConfigFile
   ( "$VarComponentFdt"          ) && VarTmp=1 || VarTmp=0
   sed -i '/VarComponentFdt/c\VarComponentFdt           = '$VarTmp'   ; install flattened device tree'               $script_dir/$VarConfigFile
   ( "$VarComponentRootfs"       ) && VarTmp=1 || VarTmp=0
   sed -i '/VarComponentRootfs/c\VarComponentRootfs        = '$VarTmp'   ; install root file system'                 $script_dir/$VarConfigFile
   ( "$VarPrepareNandFlash"      ) && VarTmp=1 || VarTmp=0
   sed -i '/VarPrepareNandFlash/c\VarPrepareNandFlash       = '$VarTmp'   ; prepare (format) the NAND data flash'    $script_dir/$VarConfigFile
   [ "$VarUpdateUBootPasswd" == "set password" ] && VarTmp=1 || VarTmp=0
   sed -i '/VarUpdateUBootPasswd/c\VarUpdateUBootPasswd      = '$VarTmp'   ; 0.. no action is performed,' $script_dir/$VarConfigFile
   ( "$VarTftpDownload"          ) && VarTmp=1 || VarTmp=0
   sed -i '/VarTftpDownload/c\VarTftpDownload   = '$VarTmp'   ; 1.. Update via TFTP'                                 $script_dir/$VarConfigFile

   if ( "$VarTftpDownload" ); then
      sed -i '/VarServerIP/c\VarServerIP       = '"'$VarServerIP'"'   ; TFTP server ip (ip of host PC)' $script_dir/$VarConfigFile
      sed -i '/VarClientIP/c\VarClientIP       = '"'$VarClientIP'"'  ; ip of '$VarTargetName''          $script_dir/$VarConfigFile
      sed -i '/VarNetMask/c\VarNetMask        = '"'$VarNetMask'"'   ; network mask'                     $script_dir/$VarConfigFile
      if [ "$VarGatewayIP" != "can stay empty" ]; then
         sed -i '/VarGatewayIP/c\VarGatewayIP      = '"'$VarGatewayIP'"'  ; gateway ip (not required when ServerIP and ClientIP are in same subnet' $script_dir/$VarConfigFile
      fi
   fi
}

######################################## EOF ######################################
