#!/bin/bash
#-----------------------------------------------------------------------------
#
#   \brief   StartTftpServer()
#
#   This function creates a config file for the TFTP server and starts, after the
#   file is created successfully, the TFTP server.
#
#   \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 StartTftpServer()
{

   filename="$script_dir/$VarTftpConfigFile"

   # Create tftp.config
   echo "service tftp" > $filename
   echo "{" >> $filename
   echo "protocol        = udp" >> $filename
   echo "port            = 69" >> $filename
   echo "socket_type     = dgram" >> $filename
   echo "wait            = yes" >> $filename
   echo "user            = root" >> $filename
   echo "server          = /usr/sbin/in.tftpd" >> $filename
   echo "server_args     = -s $VarTftpFolder" >> $filename
   echo "disable         = no" >> $filename
   echo "}" >> $filename

   # wait for process to end
   wait $!

   # Check if tftpd.config file exists
   if [  -s "$file_name" ];
   then
      echo -e "Config file for TFTP server does not exist!"
      return 1
   fi

   echo -e "Config file for TFTP server created.\n"

   # Install TFTP if necessary
   if ! type "xinetd" > /dev/null; then
      echo -e "Installing xinetd tftpd...\n"

      # install tftp server online
      OUTPUT=`echo -e "$PASSW\n" | sudo -S apt-get install xinetd tftpd`
      ret_val=$?

      # wait for process to end
      wait $!

      if [ "$ret_val" != "0" ]; then
         echo "Installing TFTP server failed."
         return 1
      fi
   fi

   echo -e "xinetd tftpd is installed.\n"

   # Killall open tftp server
   OUTPUT=`echo -e "$PASSW\n" | sudo -S killall xinetd`

   # wait for process to end
   wait $!

   # Start TFTP server
   OUTPUT=`echo -e "$PASSW\n" | sudo -S xinetd -f $filename`

   # wait for process to end
   wait $!

   echo -e "TFTP server is started.\n"

return 0
}
