#!/bin/sh
#
# Copyright (c) 2011, Intel Corporation.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms and conditions of the GNU General Public License,
# version 2, as published by the Free Software Foundation.
#
# This program is distributed in the hope it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 
# 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
#


#get input subroutine
getkey()
{
  local __error1=1
  local __error2=1
  local __returnkey=""
  local __keyvar1=""
  local __keyvar2=""
  local __input_dev

  while [ $__error1 -ne 0 -a $__error2 -ne 0 ]; do
    read -n 1 -t 1 __keyvar1
    __error1=$?
    read -n 1 -t 1 __keyvar2 <$ttyport
    __error2=$?
  done
  if [ ! -z $__keyvar1 ]; then
    __returnkey=$__keyvar1
    __input_dev="console"
  elif [ ! -z $__keyvar2 ]; then
    __returnkey=$__keyvar2
    __input_dev="serial"
  fi
  #remove ticks and dollars from input
  __returnkey=`echo $__returnkey | tr -d '\`$'`
  echo $__returnkey $__input_dev
}

getkeys()
{
  local __keyvar1=""
  if [ "$input" == "serial" ]; then
      read -r __keyvar1 <$ttyport
   else
      read -r __keyvar1
  fi
  #remove ticks and dollars from input
  __keyvar1=`echo $__keyvar1 | tr -d '\`'`
  echo $__keyvar1
}



#Display text on the console and SOL window unless input is specified
puttext()
{
  local __textvar1=$1
  if [ "$__textvar1" == "clear" ]; then
	if [ "$input" == "console" ]; then
	    	clear
        elif [ "$input" == "serial" ]; then
    		clear >$ttyport
	else
		clear
    		clear >$ttyport	
	fi
    else 
	if [ "$input" == "console" ]; then
	    	echo $__textvar1
        elif [ "$input" == "serial" ]; then
    		echo $__textvar1 >$ttyport
	else
		echo $__textvar1
		echo $__textvar1 >$ttyport
	fi
  fi
}

#mount the ideriso to /iso, copy the PARAM.XML file to /tmp and then unmount the ideriso
mountideriso ()
{
	for match in `ls /dev | grep "sr[0-4]"`; do
 	 mount0=`echo $match | grep -o "sr[0-4]"`
 	   for match0 in `dmesg | grep $mount0`; do
 	   	if [ `echo $match0 | grep "0x/0x"` ]; then
			mkdir /iso
        		mkdir /iso/$mount0
 		 	mount -t auto /dev/$mount0 /iso/$mount0 2>>/tmp/errors.log
 		 	error=$?
			cp /iso/$mount0/PARAM.XML /tmp/PARAM.XML
			umount /iso/$mount0
    		fi
    	   done
	done
}


#create the menu of valid images
createimagelist ()
{
	rm -f /tmp/imagelist
	rm -f /tmp/validimages	

	ls /mnt >tmp/imagelist
	awk 'tolower($0) ~ /.hd/' /tmp/imagelist >>/tmp/validimages
	awk 'tolower($0) ~ /.iso/' /tmp/imagelist >>/tmp/validimages
	awk 'tolower($0) ~ /.img/' /tmp/imagelist >>/tmp/validimages

	maxfilenumber=`awk 'END {print NR}' /tmp/validimages`
}
	
#display the menu and stop after $rowstodisplay
displaymenu ()
{
	maxfilenumber=`awk 'END {print NR}' /tmp/validimages`
	i=1
	while [ "$i" -le "$maxfilenumber" ]
	    do
		 if [ "$RIL" == "1" ]; then
		    echo "" >$ttyport
		    echo "MENU_CREATE_ITEM "$i >$ttyport
		    echo "MENU_SET_ITEM_TITLE "$i" "`cat /tmp/validimages |sed $i'q;d'` >$ttyport
		    echo "MENU_SET_ITEM_RETVAL "$i" "$i >$ttyport
		  else   
		    puttext " "$i"  "`cat /tmp/validimages |sed $i'q;d'`
		    rowstodisplay=20
		    divisible=$(($i % $rowstodisplay))
			if [ $divisible == "0" ] && [ $i -ge $rowstodisplay ]; then
			   puttext "Press enter to continue"
			   continue=$(getkeys)
			fi  
		 fi
	      i=$((i + 1)) 
	done 
	if [ "$RIL" == "1" ]; then
		    echo "" >$ttyport
		    echo "MENU_CREATE_ITEM "$i >$ttyport
		    echo "MENU_SET_ITEM_TITLE "$i" "try a different share >$ttyport
		    echo "MENU_SET_ITEM_RETVAL "$i" "0 >$ttyport
	fi
}

#parsemethod for xml file
parseparamxml ()
{
  local __input=$1
  local __result=""
	if [ -f /tmp/PARAM.XML ]; then
		result=`cat /tmp/PARAM.XML | grep "<$__input>" | grep -o ">.*<" | grep -o "[-._$ A-Za-z0-9].*[-._$ A-Za-z0-9]"`
		echo $result
		#Debug information sent to /tmp/progress.txt file
		echo `date`" PARAM.XML Exists" $__input $result >>/tmp/progress.txt
	fi
}

#parse the xml file and retrieve variables
retrievexmlvar ()
{
	input=`parseparamxml "input"`
	downloadtype=`parseparamxml "downloadtype"`
	authentication=`parseparamxml "authentication"`
	username=`parseparamxml "username"`
	password=`parseparamxml "password"`
	domain=`parseparamxml "domain"`
	path=`parseparamxml "path"`
	image=`parseparamxml "image"`
}

#reset variables
resetvar ()
{
	path=""
	username=""
	domain=""
	password=""
	image=""
	authentication=""
	downloadtype=""
}


#get link speed
linkspeed ()
{
  linkspeeddisplay=`ethtool eth0 | grep -i speed`
}

#display speed to end user
displayspeed ()
{
	linkspeeddisplay=`ethtool eth0 | grep -i speed`
	if [ "$RIL" == "1" ]; then
		echo "" >$ttyport
		echo "POPUP LAN Link "$linkspeeddisplay >$ttyport
		echo "" >$ttyport
        fi
	puttext "LAN Link "$linkspeeddisplay	

}

#display a message on the inactive component
displaymessage ()
{
	if [ "$input" == "serial" ] || [ "$RIL" == "1" ]; then
		clear
		echo "  ****************************************************************************"
	  	echo "  **     2 stage boot is accepting input from a remote computer             **"
	  	echo "  ****************************************************************************"
	elif [ "$input" == "console" ]; then
		clear >$ttyport
		echo "  ****************************************************************************" >$ttyport
	  	echo "  **     2 stage boot is accepting input from the local computer            **" >$ttyport
	  	echo "  ****************************************************************************" >$ttyport
        fi
}

renegotiatelinkspeed ()
{
	linkspeed=`ethtool eth0 | grep -i speed | grep -o 10Mb`
	if [ "$RIL" == "1" ] && [ "$renegotiate" == "1" ] && [ "$linkspeed" == "10Mb" ] && [ $imagesize -gt 20000 ]; then
	     echo "" >$ttyport
	     echo "DISCONNECT_AND_RECONNECT 9" >$ttyport
	     read -t 4 pause
	     ethtool -r eth0
	     echo "Renegotiating Link Speed" 
	     read -t 5 pause
	     displayspeed
	fi
}

wgetimagesize ()
{
		tempimagesize=`cat /tmp/wgetlog | grep Length | awk '{print $2}'`

		if [ "$tempimagesize" != "" ]; then
		imagesize=$(($tempimagesize / 1024))
		renegotiatelinkspeed
		fi

}

wgetimage ()
{
rm /tmp/wgetlog -f
touch /tmp/wgetlog
if [ "$authentication" == "" ] ; then
	if [ "$RIL" == "1" ]; then
		echo "" >$ttyport
		echo "MENU_SET_DESC Will you supply web server authentication credentials" >$ttyport
		echo "MENU_SHOW" >$ttyport
		echo "" >$ttyport
		echo "MENU_CREATE_ITEM 1" >$ttyport
		echo "MENU_SET_ITEM_TITLE 1 Yes" >$ttyport
		echo "MENU_SET_ITEM_RETVAL 1 yes" >$ttyport
		echo "MENU_CREATE_ITEM 2" >$ttyport
		echo "MENU_SET_ITEM_TITLE 2 No" >$ttyport
		echo "MENU_SET_ITEM_RETVAL 2 no" >$ttyport
		read -r authentication <$ttyport
		echo "" >$ttyport
		echo "MENU_CLEAR" >$ttyport
	    else 
		menuselection=0
		while [ $menuselection -lt 1  ] || [ $menuselection -gt 2 ]; do
			puttext clear
			puttext "Will you supply web server authentication credentials"
			puttext "1. Yes"
			puttext "2. No"
			puttext "Enter the number for your selection"
			menuselection=$(getkeys)
#			Check for valid input............
			if [ "$menuselection" == "" ]; then
				menuselection=0
				elif [ $menuselection == ${menuselection//[^0-9,]/} ]; then
				menuselection=$menuselection
				else
				menuselection=0
			fi
		done 
		if [ "$menuselection" == "1" ]; then
		        authentication="yes"
		elif [ "$menuselection" == "2" ]; then
			authentication="no"
		fi
	fi
fi

#Obtain the username for the webserver
if [ "$authentication" == "yes" ];then
	if [ "$username" == "" ]; then
		if [ "$RIL" == "1" ]; then
			echo "" >$ttyport
			echo "REQUEST_INPUT Enter your username" >$ttyport
			read -r username <$ttyport
		   else
			puttext "Enter your username then press enter  "
			username=$(getkeys)
		fi
	fi

#Obtain the password for the network share
	if [ "$password" == "" ]; then
		if [ "$RIL" == "1" ]; then
			echo "" >$ttyport
			echo "REQUEST_INPUT Enter your password" >$ttyport
			read -r password <$ttyport
		   else
			puttext "Enter your password then press enter  "
			password=$(getkeys)
		fi
	fi
fi

	
	if [ "$path" == "" ]; then
		if [ "$RIL" == "1" ]; then
			echo "" >$ttyport
			echo "REQUEST_INPUT Enter the webserver URL" >$ttyport
			read -r path <$ttyport
		   else
			puttext ""
			puttext "Enter your webserver URL then press enter  "
			path=$(getkeys)
		fi
	fi	

#Parse the URL for a file extension
	image=`echo $path | sed 's/.*\(http[^ ]*\).*/\1/'`
	image=`basename $image`
	imagetype=`echo /mnt/$image | grep -o '\.[^.]*$'`

#check if the image has extension .iso, .hd. or .img
	if [ `echo $imagetype | tr [:upper:] [:lower:]` =  `echo .iso | tr [:upper:] [:lower:]` ] || [ `echo $imagetype | tr [:upper:] [:lower:]` =  `echo .hd | tr [:upper:] [:lower:]` ] || [ `echo $imagetype | tr [:upper:] [:lower:]` =  `echo .img | tr [:upper:] [:lower:]` ] || [ `echo $imagetype | tr [:upper:] [:lower:]` =  `echo .iso | tr [:upper:] [:lower:]` ]; then

		if [ "$authentication" == "yes" ];then
			sh -c "wget --spider --user=$username --password=$password $path -o /tmp/wgetlog"
		   else
			sh -c "wget --spider $path -o /tmp/wgetlog"
		fi
		
		wgetimagesize
	
		#Debug information sent to /tmp/progress.txt file
		echo `date`" Imagesize= "$imagesize >>/tmp/progress.txt 

		if [ "$authentication" == "yes" ];then
			sh -c "wget --user=$username --password=$password $path -O /mnt/$image"
		          else
			sh -c "wget $path -O /mnt/$image"
		fi
		wgeterror=$?

		if [ $wgeterror -ne 0 ]; then
       			puttext ""
        		puttext "*** Could Not Retrieve Image ***"
        		puttext "Error return code is "$wgeterror 
			if [ "$RIL" == "1" ]; then
				echo "" >$ttyport
				echo "POPUP Error: Could not retrieve image from web server.  WGET Error Code: "$wgeterror>$ttyport
				echo "" >$ttyport
			fi
  		fi

		#Debug information sent to /tmp/progress.txt file
		echo `date`" Webserver Download Complete " >>/tmp/progress.txt

	#if we could not determine image type from url parsing try to use the mimetype.  If we can't get from mimetype, then assume .iso
	else 

		image=tmpimage

		if [ "$authentication" == "yes" ];then
			sh -c "wget --spider --user=$username --password=$password $path -o /tmp/wgetlog"
		   else
			sh -c "wget --spider $path -o /tmp/wgetlog"
		fi

		wgetimagesize

		if [ "$authentication" == "yes" ];then
			sh -c "wget --user=$username --password=$password $path -O /mnt/$image"
		          else
			sh -c "wget $path -O /mnt/$image"
		fi
		wgeterror=$?

		if [ $wgeterror -ne 0 ]; then
       			puttext ""
        		puttext "*** Could Not Retrieve Image ***"
        		puttext "Error return code is "$wgeterror 
			if [ "$RIL" == "1" ]; then
				echo "" >$ttyport
				echo "POPUP Error: Could not retrieve image from web server.  WGET Error Code: "$wgeterror>$ttyport
				echo "" >$ttyport
			fi
  		fi

	#parse wget log for mimetype and append to tmpimage
		imagetype=`grep Length /tmp/wgetlog | sed -e 's|.*\[.*/\(.*\)\].*|\1|'`
		
		if [ `echo $imagetype | tr [:upper:] [:lower:]` =  `echo iso | tr [:upper:] [:lower:]` ] || [ `echo $imagetype | tr [:upper:] [:lower:]` =  `echo hd | tr [:upper:] [:lower:]` ] || [ `echo $imagetype | tr [:upper:] [:lower:]` =  `echo .img | tr [:upper:] [:lower:]` ] || [ `echo $imagetype | tr [:upper:] [:lower:]` =  `echo iso | tr [:upper:] [:lower:]` ]; then
			mv /mnt/$image /mnt/"$image"."$imagetype"
			image="$image""$imagetype"
		
		else
			mv /mnt/$image /mnt/"$ima	#remove ticks and dollars from input
	__returnkey=`echo $__returnkey | tr -d '\`$'`ge"".iso"
			image="$image"".iso"
		fi
	fi

	if [ $wgeterror -ne 0 ]; then
		filegetstatus=0
		resetvar
	else
		mv /mnt/$image /tmp/$image
		filegetstatus=1
	fi

}

#==================================================================================================================================================

cifsimage ()
{
filegetstatus=0
mountsuccess=0
mounterror=0
submounterror=0

#Determine the path to the network share containing the stage 2 images
	if [ "$path" == "" ]; then
		if [ "$RIL" == "1" ]; then
			echo "" >$ttyport
			echo "REQUEST_INPUT Enter the path to your share drive" >$ttyport
			read -r path <$ttyport
		   else
			puttext "Enter the path to your shared drive then press enter  "
			path=$(getkeys)
		fi
	fi
#change all \ to / and then remove leading //
path=$(echo $path | sed 's:\\:/:g')
path=$(echo $path | sed 's:^/::')
path=$(echo $path | sed 's:^/::')

echo `date`" path "$path >>/tmp/progress.txt

rootpath=`echo $path | sed 's|\([-._$ 0-9A-Za-z]*/[-._$ 0-9A-Za-z]*\)/.*|\1|'`
subpath=`echo $path | sed 's|^[-._$ 0-9A-Za-z]*/[-._$ 0-9A-Za-z]*/||'`

if [ "$rootpath" == "$subpath" ]; then
	subpath=""
fi

echo `date`" rootpath "$rootpath >>/tmp/progress.txt
echo `date`" subpath "$subpath >>/tmp/progress.txt

#Obtain the domain for the network share
	if   [ "$domain" == "" ] && [ "$username" != "" ]; then
		domain="emptydomain"
	   elif [ "$domain" == "" ]; then
		if [ "$RIL" == "1" ]; then
			echo "" >$ttyport
			echo "REQUEST_INPUT Enter your domain" >$ttyport
			read -r domain <$ttyport
		   else
			puttext "Enter your domain then press enter  "
			domain=$(getkeys)
		fi
	fi

echo `date`" domain name "$domain >>/tmp/progress.txt

#Obtain the username for the network share
	if [ "$username" == "" ]; then
		if [ "$RIL" == "1" ]; then
			echo "" >$ttyport
			echo "REQUEST_INPUT Enter your username" >$ttyport
			read -r username <$ttyport
		   else
			puttext "Enter your username then press enter  "
			username=$(getkeys)
		fi
	#remove ticks and dollars from input
	username=`echo $username | tr -d '\`$'`
	fi

echo `date`" username "$username >>/tmp/progress.txt

#Obtain the password for the network share
	if [ "$password" == "" ]; then
		if [ "$RIL" == "1" ]; then
			echo "" >$ttyport
			echo "REQUEST_INPUT Enter your password" >$ttyport
			read -r password <$ttyport
		   else
			puttext "Enter your password then press enter  "
			password=$(getkeys)
		fi
	fi

mount -t cifs //$rootpath /tempmnt -o username=$username,pass=$password,domain=$domain,noserverino,nounix,ro 2>>/tmp/error.log
mounterror=$?
mount -o bind /tempmnt/$subpath /mnt
submounterror=$?

  if [ $mounterror -ne 0 ] || [ $submounterror -ne 0 ]; then
        puttext ""
        puttext "*** Mount not successful ***"
        puttext "Error return code is "$mounterror 
	puttext `cat /tmp/error.log`
	puttext "path:"$path" username:"$username" password:"$password" domain:"$domain" image:"$image
	if [ "$RIL" == "1" ]; then
		echo "" >$ttyport
		echo "POPUP Error: Could not mount the network drive" >$ttyport
		echo "" >$ttyport
	fi
	resetvar
	mountsuccess=0
	filegetstatus=0
	umount /mnt
	umount /tempmnt
  else
	mountsuccess=1
	filegetstatus=1
  fi


#continue only if there were no errors during mount
if [ "$mountsuccess" = "1" ]; then
	#determine the image to be booted
		if [ "$image" != "" ] && [ ! -e "/mnt/$image" ]; then
			puttext "Error: Could not find "$image
			if [ "$RIL" == "1" ]; then
				echo "" >$ttyport
				echo "POPUP Error: Could not find "$image>$ttyport
			fi
			image=""
		fi
		if [ "$image" == "" ];then
			createimagelist
			if [ "$RIL" == "1" ]; then
				echo "" >$ttyport
				echo "MENU_SET_DESC Available Images" >$ttyport
				displaymenu
				echo "MENU_SHOW" >$ttyport
				read linenumber <$ttyport
				echo "" >$ttyport
				echo "MENU_CLEAR" >$ttyport
			  else
				linenumber=-1
				maxfilenumber=`awk 'END {print NR}' /tmp/validimages`
				puttext "linenumber "$linenumber
				while [ $linenumber -lt 0  ] || [ $linenumber -gt $maxfilenumber ]; do
					puttext clear
					puttext "Available Images"
					displaymenu
					puttext "Enter a number to boot an image"
					puttext "Press enter to display the menu again"
					puttext "Press 0 to search a different location"
					linenumber=$(getkeys)
				#	Check for valid input............
					if [ "$linenumber" == "" ]; then
						linenumber=$((maxfilenumber + 1)) 
					elif [ $linenumber == ${linenumber//[^0-9,]/} ]; then
						linenumber=$linenumber
					else
						linenumber=-1
					fi 	
				done
			fi

			if [ "$linenumber" == "0" ]; then
				filegetstatus=0
				resetvar
				umount /mnt
				umount /tempmnt
			else
				image=`cat /tmp/validimages |sed $linenumber'q;d'`
				filegetstatus=1
			fi
		fi

	if [ "$filegetstatus" == "1" ]; then
	#add file exists here...... and display message that file does not exist
	imagesize=`du /mnt/$image -c | grep -i total | grep -o '[0-9].*[0-9]'`
	#Debug information sent to /tmp/progress.txt file
	echo `date`" Imagesize= "$imagesize >>/tmp/progress.txt
	
	renegotiatelinkspeed	

	bar --in-file /mnt/$image | dd of=/tmp/$image
	copyerror=$?
       	umount /mnt
	umount /tempmnt
		if [ $copyerror -ne 0 ]; then
			filegetstatus=0
			resetvar
		else
			filegetstatus=1
		fi
	fi
fi

}

#--------------------------------------------------------------------------------------------------------
#Begin Script Here
#--------------------------------------------------------------------------------------------------------

#disable dmesg statements
dmesg -n 1

mkdir /tempmnt
mkdir /lib/modules/`uname -r`/
IFS=$'\n'
ttyport=""
touch /etc/progress.txt
echo `date`"Progress File Created " >>/tmp/progress.txt

echo 0 > /proc/fs/cifs/OplockEnabled

#determine the ttyS port used by vPro client
for match in `dmesg | grep "ttyS[0-3]"`; do
      port0=`echo $match | grep -o "ttyS[0-3]"`
      if [ `echo $match | grep -i "I/O"` ]; then
        if [ `echo $match | grep -i "0x3F8"` ] || [ `echo $match | grep -i "0x2F8"` ] || [ `echo $match | grep -i "0x3E8"` ] || [ `echo $match | grep -i "0x2E8"` ]; then
          :
        else
          ttyport="/dev/"$port0
        fi
      fi
done

echo `date`" ttyS port is "$ttyport >>/tmp/progress.txt

#check if the remote serial port is present on the system.  Halt if it is not.
if [ "$ttyport" = "" ]; then
  clear
  echo "  ****************************************************************************"
  echo "  **   2 stage boot for PCs featuring Intel(r) vPro(tm) technology   **"
  echo "  **                                                                        **"
  echo "  **      A remote serial connection was not found on this system.          **"
  echo "  **    2 stage boot requires this connection and will now halt.      **"
  echo "  ****************************************************************************"
  while true; do
    :
  done
fi

  # Let the console know that the iso is booted and running on an AMT machine
  echo "AWK" >$ttyport
  # Find and mount the AMT virtual CDROM
  mountideriso


#Determine if we are working with the Remote ISO Launcher launching utility
echo "" >$ttyport
echo "ECHO %APP_NAME%" >$ttyport
read -t 5 RIL <$ttyport

#Debug information sent to /tmp/progress.txt file
echo `date`" RIL= "$RIL >>/tmp/progress.txt

if [ "$RIL" == "RIL" ]; then
	RIL=1
	input="serial"
	echo "" >$ttyport        
	echo "ECHO %LINK_RENEGOTIATE%" >$ttyport
	read -t 2 renegotiate <$ttyport
else 
	RIL=0
fi
puttext clear

#Debug information sent to /tmp/progress.txt file
echo `date`" RIL= "$RIL >>/tmp/progress.txt

retrievexmlvar

skipinputmethod=0
if [ "$downloadtype" == "share" ] && [ "$username" != "" ] && [ "$password" != "" ] && [ "$path" != "" ] && [ "$image" != "" ]; then
  skipinputmethod=1
elif [ "$downloadtype" == "web" ] && [ "$authentication" == "yes" ] && [ "$password" != "" ] && [ "$username" != "" ] && [ "$path" != "" ]; then
  skipinputmethod=1
elif [ "$downloadtype" == "web" ] && [ "$authentication" == "no" ] && [ "$path" != "" ]; then
  skipinputmethod=1
fi

#Determine if input is coming from local console or remote
	if [ "$RIL" != "1" ] && [ "$skipinputmethod" == "0" ] && [ "$input" == "" ]; then
		puttext "  ****************************************************************************"
		puttext "  **   2 stage boot for PCs featuring Intel(r) vPro(tm) technology          **"
		puttext "  ****************************************************************************"
		puttext "Press 'c' to continue"
		temp1=$(getkey)
#		input2=`echo "$temp1" | awk '{print $1}'`
		input1=`echo "$temp1" | awk '{print $2}'` 
		input=$input1
		puttext clear
	fi

displaymessage

#filegetstatus determines whether or not the file download was successful.  If failed, then retry.
filegetstatus=0
while [ "$filegetstatus" == "0" ]; do

	#get retrieval method
	echo `date`" downloadtype= "$downloadtype >>/tmp/progress.txt

	if [ "$downloadtype" == "" ] ; then
		if [ "$RIL" == "1" ]; then
			echo "" >$ttyport
			echo "MENU_SET_DESC Choose image location" >$ttyport
			echo "MENU_SHOW" >$ttyport
			echo "" >$ttyport
			echo "MENU_CREATE_ITEM 1" >$ttyport
			echo "MENU_SET_ITEM_TITLE 1 Webserver" >$ttyport
			echo "MENU_SET_ITEM_RETVAL 1 web" >$ttyport
			echo "MENU_CREATE_ITEM 2" >$ttyport
			echo "MENU_SET_ITEM_TITLE 2 Network File Share" >$ttyport
			echo "MENU_SET_ITEM_RETVAL 2 share" >$ttyport
			read -r downloadtype <$ttyport
			echo "" >$ttyport
			echo "MENU_CLEAR" >$ttyport
		    else 
			menuselection=0
			while [ $menuselection -lt 1  ] || [ $menuselection -gt 2 ]; do
				puttext "Image Download Location"
				puttext "1. Webserver"
				puttext "2. Network File Share"
				puttext "Enter the number for your image location"
				menuselection=$(getkeys)
#				Check for valid input............
				if [ "$menuselection" == "" ]; then
					menuselection=0
					elif [ $menuselection == ${menuselection//[^0-9,]/} ]; then
					menuselection=$menuselection
					else
					menuselection=0
				fi
			done 
			if [ "$menuselection" == "1" ]; then
			        downloadtype="web"
			elif [ "$menuselection" == "2" ]; then
				downloadtype="share"
			fi
		fi
	fi
		echo `date`" download method "$downloadtype >>/tmp/progress.txt
	
		if [ "$downloadtype" == "web" ]; then
				wgetimage
			elif [ "$downloadtype" == "share" ]; then
				cifsimage
		fi
	
done
	
	if [ "$RIL" == "1" ]; then
		linkspeed
		echo "" >$ttyport
		echo "POPUP Loading "$image "LAN Link "$linkspeeddisplay >$ttyport
        fi

	
	#flush cached memory
	sync
	echo 3 > /proc/sys/vm/drop_caches
	 
	#establish which type of image was selected (.hd, .iso, or .img or .xml)
	imagetype=`echo /tmp/$image | grep -o '\.[^.]*$'`

	echo `date`" image "$image >>/tmp/progress.txt

	#Debug information sent to /tmp/progress.txt file
	echo `date`" Imagetype= "$imagetype >>/tmp/progress.txt
    
        if [ `echo $imagetype | tr [:upper:] [:lower:]` =  `echo .iso | tr [:upper:] [:lower:]` ]; then
	   	kexec -l /sbin/grub.exe --initrd=/tmp/$image --command-line="--config-file=map --mem (rd)+1 (0xff); map --hook; chainloader (0xff)"
	   elif [ `echo $imagetype | tr [:upper:] [:lower:]` =  `echo .img | tr [:upper:] [:lower:]` ]; then
	   	kexec -l /sbin/grub.exe --initrd=/tmp/$image --command-line="--config-file=map (rd)+1 (fd0); map --hook; chainloader (fd0)+1; rootnoverify (fd0)"
	   elif [ `echo $imagetype | tr [:upper:] [:lower:]` =  `echo .hd | tr [:upper:] [:lower:]` ]; then
	   	kexec -l /sbin/grub.exe --initrd=/tmp/$image --command-line="--config-file=map (rd)+1 (hd0); map --hook; rootnoverify (hd0,0); chainloader /ntldr"
	fi
	#Debug information sent to /tmp/progress.txt file
	echo `date`" Mark: After loading image to memory" >>/tmp/progress.txt	

	puttext "Loading Complete.  Booting "$image
	if [ "$RIL" == "1" ]; then
		echo "" >$ttyport
		echo "POPUP Loading Complete. Booting "$image >$ttyport
		echo "" >$ttyport
	fi

	ifconfig eth0 down

	#Debug information sent to /tmp/progress.txt file
	echo `date`" Between ifconfig eth0 down and kexec -e" >>/tmp/progress.txt

	if [ $error -eq 0 ]; then
	kexec -e
	fi
	

