#!/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
AWK=/usr/bin/awk
BDATE=/bin/date
CAT=/bin/cat
CLEAR=/usr/bin/clear
DMESG=/bin/dmesg
#ECHO=echo # echo is a shell builtin
FDISK=/sbin/fdisk
FOLD=/usr/bin/fold
GREP=/bin/grep
HEAD=/usr/bin/head
IETADM=/usr/sbin/ietadm
IETD=/usr/sbin/ietd
IFCONFIG=/sbin/ifconfig
INSMOD=/sbin/insmod
KILLALL=/usr/bin/killall
LS=/bin/ls
MKDIR=/bin/mkdir
MKTEMP=/bin/mktemp
MOUNT=/bin/mount
MV=/bin/mv
TOUCH=/bin/touch
TR=/usr/bin/tr
UMOUNT=/bin/umount
UNAME=/bin/uname

checkreturn()
{
  retval=$?
  if [ $retval -ne 0 ]; then
	echo " failure code "$retval >>$TMPFILE.txt
	echo "Function failure return code "$retval >$ttyport
		while true; do
		    :
		done
  fi

}

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
}

#display a message on the inactive component
displaymessage ()
{
	if [ "$input" == "serial" ] || [ "$RIL" == "1" ]; then
		${CLEAR}
		echo "  ****************************************************************************"
	  	echo "  **     Remote Drive Mount is accepting input from a remote computer       **"
	  	echo "  ****************************************************************************"
	elif [ "$input" == "console" ]; then
		${CLEAR} >$ttyport
		echo "  ****************************************************************************" >$ttyport
	  	echo "  **     Remote Drive Mount is accepting input from the local computer      **" >$ttyport
	  	echo "  ****************************************************************************" >$ttyport
       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=$?
			${UMOUNT} /iso/$mount0
    		fi
    	   done
	done
}

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

IFS=$'\n'
ttyport=""
PATH=""
export PATH=$PATH:/sbin:/usr/sbin:/bin:/usr/bin
#disable dmesg statements
${DMESG} -n 1
linuxver=`${UNAME} -r`
${MKDIR} /lib/modules/$linuxver
checkreturn
${MV} /lib/modules/iscsi_trgt.ko /lib/modules/$linuxver/
checkreturn
TMPFILE=`${MKTEMP}`
#${TOUCH} $TMPFILE.txt

#Identify the Intel AMT Serial Port
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

#Debug information sent to $TMPFILE.txt file
echo `${BDATE}`" ttyport= "$ttyport >>$TMPFILE.txt

if [ "$ttyport" = "" ]; then
  ${CLEAR}
  echo "  ****************************************************************************"
  echo "  **   Remote Drive Mount for PCs featuring Intel(r) vPro(tm) technology    **"
  echo "  **                                                                        **"
  echo "  **      A remote serial connection was not found on this system.          **"
  echo "  **    Remote Drive Mount requires this connection and will now halt.      **"
  echo "  ****************************************************************************"
  while true; do
    :
  done
else
  # Let the console know that the iso is booted and running on an AMT machine
  echo "AWK" >$ttyport
fi

#Determine if we are working with the Remote ISO Launcher launching utility
echo "" >$ttyport
echo "ECHO %APP_NAME%" >$ttyport
read -t 4 RIL <$ttyport
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

#Determine if input is coming from local console or remote
	if [ "$RIL" != "1" ]; then
		if [ "$input" == "" ]; then
			puttext "  ****************************************************************************"
		  	puttext "  **   Remote Drive Mount 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" | /usr/bin/awk '{print $2}'` 
			input=$input1
			puttext clear
		fi
	fi
#Debug information sent to $TMPFILE.txt file
echo `${BDATE}`" input= "$input >>$TMPFILE.txt
displaymessage

#Debug information sent to $TMPFILE.txt file
echo `${BDATE}`" RIL= "$RIL >>$TMPFILE.txt

#mountideriso

puttext clear
displaymessage

error=99

ipaddr=`${IFCONFIG} eth0 | ${GREP} inet | ${AWK} -F: '{ print $2 }' | ${AWK} '{ print $1 }'`

#  hostname vPro
sessionid=`${BDATE} +%m%d%y%H%M%S`
yearmonth=`${BDATE} -I | ${GREP} -o "^.*-" | ${GREP} -o "^.*[0-9]"`
chappassword=`${CAT} /dev/urandom| ${TR} -dc 'a-zA-Z0-9' | ${FOLD} -w 13| ${HEAD} -n 1`

${TOUCH} /etc/ietd.conf

echo Target iqn.$yearmonth.vPro:$sessionid>>/etc/ietd.conf
echo IncomingUser itproadmin $chappassword>>/etc/ietd.conf

puttext "  ****************************************************************************"
puttext "  **    Remote Drive Mount for PCs featuring Intel(r) vPro(tm) technology   **" 
puttext "  **                                                                        **" 
puttext "  **                  Available Disks to Remotely Mount                     **" 
puttext "  ****************************************************************************" 
puttext ""

var=0
for match in `${FDISK} -l`; do
	if [ `echo $match | ${GREP} "Disk /dev"` ]; then
		if [ `echo $match | ${GREP} "GB,"` ]; then
			diskid=`echo $match | ${GREP} -o "sd[a-d]"`
			puttext "             "$match
			echo Lun $var Path=/dev/$diskid,Type=blockio>>/etc/ietd.conf
			var=$((var + 1))
		fi
	fi
done

if [ $var == 0 ]; then
	puttext "No Hard Drives were found on this system.  Remote Drive Mount requires at least one Hard Drive"
	if [ $RIL == 1 ]; then
		echo "">$ttyport
		echo "POPUP No Hard Drives were found on this system.  Remote Drive Mount requires at least one Hard Drive" >$ttyport
		echo "" >$ttyport
	fi
  while true; do
    :
  done
fi

${INSMOD} /lib/modules/$linuxver/iscsi_trgt.ko
checkreturn
${IETD} --config=/etc/ietd.conf --address=$ipaddr
checkreturn

puttext ""
puttext "  ****************************************************************************"
puttext "  iSCSI Connection Information"
puttext "	     Client IP Address: $ipaddr"
puttext "	     Chap Username: itproadmin"
puttext "	     Chap Password: $chappassword"
puttext "	     iSCSI IQN: iqn.$yearmonth.vpro:storage.$sessionid"
puttext "  ****************************************************************************"
puttext "  Command line: "
puttext "  iscsicli qaddtargetportal $ipaddr"
puttext "  Command line: "
puttext "  iscsicli qlogintarget iqn.$yearmonth.vpro:$sessionid itproadmin $chappassword"
puttext "  ****************************************************************************"

if [ $RIL == 1 ]; then
	echo "" >$ttyport
	echo "BATCH iscsi.bat $ipaddr iqn.$yearmonth.vpro:$sessionid itproadmin $chappassword" >$ttyport
	echo "" >$ttyport
fi

puttext "  ****************************************************************************"
puttext "             Press Enter to stop your remote drive mount session"
puttext "  ****************************************************************************"

stop=$(getkeys)

${IETADM} --op delete
${KILLALL} ietd

echo "  ****************************************************************************" >$ttyport
echo "  **            Remote Drive Mount session has been stopped                 **" >$ttyport
echo "  ****************************************************************************" >$ttyport

echo "  ****************************************************************************"
echo "  **            Remote Drive Mount session has been stopped                 **"
echo "  ****************************************************************************"
