#!/bin/sh
#
# Remote Drive Erase
# 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
}

#parse the PARAM.XML file and retrieve 
parseparamxml ()
{
  local __input=$1
  local __result=""
	if [ -f /tmp/PARAM.XML ]; then
		result=`awk -F"[<>]" '/'$__input'/{print $3}' /tmp/PARAM.XML`
		echo $result
	fi
}

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

#send email
sendemail ()
{
  local __input=$1

  echo "to: "$recipient >/tmp/email.txt
  if [ "$subject" == "" ]; then
  	echo "subject: RDE Session: "$session_id >>/tmp/email.txt
  else
  	echo "subject: RDE Session: "$session_id" - "$subject >>/tmp/email.txt
  fi
  echo "" >>/tmp/email.txt
  echo $__input >>/tmp/email.txt
  echo "" >>/tmp/email.txt

  print2mail=0
  for match in `dmidecode`; do
    if [ `echo $match | grep "System Information"` ]; then
      echo $match >>/tmp/email.txt
      print2mail=1
    elif [ $print2mail -eq 1 ]; then
      if [ `echo $match | grep "Family"` ]; then
        echo $match >>/tmp/email.txt
        print2mail=0
      else
        echo $match >>/tmp/email.txt
      fi
    fi
  done
  echo "" >>/tmp/email.txt

	valid=0
  echo "Drive Information" >>/tmp/email.txt
  for match0 in `fdisk -l`; do
    if [ `echo $match0 | grep "Disk /dev"` ]; then
			if [ `echo $match0 | grep "GB,"` ]; then
				valid=1
			elif [ `echo $match0 | grep "MB,"` ]; then
				valid=0
			fi
      if [ `echo $match0 | grep "doesn't contain"` ] && [ $valid -eq 1 ]; then
        echo "        "$match0 >>/tmp/email.txt
				echo "" >>/tmp/email.txt
      elif [ $valid -eq 1 ]; then
        echo "        "$match0 >>/tmp/email.txt
        mount0=`echo $match0 | grep -o "/dev/sd[a-d]"`
        echo "        "`hdparm -i $mount0 2>>/tmp/errors.log | grep -o 'Model=.[^,]*,' | grep -o '^.*[A-Za-z0-9]'` >>/tmp/email.txt
        echo "        "`hdparm -i $mount0 2>>/tmp/errors.log | grep -o 'FwRev=.[^,]*,' | grep -o '^.*[A-Za-z0-9]'` >>/tmp/email.txt
        echo "        "`hdparm -i $mount0 2>>/tmp/errors.log | grep -o 'SerialNo=.*'` >>/tmp/email.txt
				echo "" >>/tmp/email.txt
      fi
    fi
  done
  echo "" >>/tmp/email.txt

	if [ "$server" != "" ]; then
		if [ "$encryption" == "none" ]; then
			if [ "$authentication" == "yes" ]; then
				CMD="cat /tmp/email.txt | sendmail -S "$server":"$port" -f "$sender" -au"$username" -ap"$password" 2>>/tmp/errors.log"
				eval $CMD
			elif [ "$authentication" == "no" ]; then
				CMD="cat /tmp/email.txt | sendmail -S "$server":"$port" -f "$sender" 2>>/tmp/errors.log"
				eval $CMD
			fi
		elif [ "$encryption" == "ssl" ]; then
			if [ "$authentication" == "yes" ]; then
				CMD="cat /tmp/email.txt | sendmail -H 'exec openssl s_client -quiet -CApath /etc/ssl/certs -connect "$server":"$port" -tls1' -f "$sender" -au"$username" -ap"$password" 2>>/tmp/errors.log"
				eval $CMD
			elif [ "$authentication" == "no" ]; then
				CMD="cat /tmp/email.txt | sendmail -H 'exec openssl s_client -quiet -CApath /etc/ssl/certs -connect "$server":"$port" -tls1' -f "$sender" 2>>/tmp/errors.log"
				eval $CMD
			fi
		elif [ "$encryption" == "tls" ]; then
			if [ "$authentication" == "yes" ]; then
				CMD="cat /tmp/email.txt | sendmail -H 'exec openssl s_client -quiet -CApath /etc/ssl/certs -connect "$server":"$port" -tls1 starttls smtp' -f "$sender" -au"$username" -ap"$password" 2>>/tmp/errors.log"
				eval $CMD
			elif [ "$authentication" == "no" ]; then
				CMD="cat /tmp/email.txt | sendmail -H 'exec openssl s_client -quiet -CApath /etc/ssl/certs -connect "$server":"$port" -tls1 starttls smtp' -f "$sender" 2>>/tmp/errors.log"
				eval $CMD
			fi
		fi
	fi
}

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

#disable dmesg statements
dmesg -n 1

mkdir /lib/modules/`uname -r`/
IFS=$'\n'
ttyport=""
session_id=`date +%m%d%y%H%M%S`

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

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

ifconfig eth0
if [ $? -ne 0 ]; then
  puttext "clear"
  puttext "  ****************************************************************************"
  puttext "  **   Remote Drive Erase for PCs featuring Intel(r) vPro(tm) technology    **"
  puttext "  **                                                                        **"
  puttext "  **   An appropriate Intel network adapter was not found on this system.   **"
  puttext "  **      Remote Drive Erase requires this adapter and will now halt.       **"
  puttext "  ****************************************************************************"
  while true; do
    :
  done
fi

if [ ! `fdisk -l | grep "sda:"` ]; then
  puttext "clear"
  puttext "  ****************************************************************************"
  puttext "  **   Remote Drive Erase for PCs featuring Intel(r) vPro(tm) technology    **"
  puttext "  **                                                                        **"
  puttext "  **       No available Device/Partitions were found on this system.        **"
  puttext "  **   Remote Drive Erase requires an available device and will now halt.   **"
  puttext "  ****************************************************************************"
  while true; do
    :
  done
fi

if [ ! `ifconfig eth0 | grep "inet addr"` ]; then
  puttext "clear"
  puttext "  ****************************************************************************"
  puttext "  **   Remote Drive Erase for PCs featuring Intel(r) vPro(tm) technology    **"
  puttext "  **                                                                        **"
  puttext "  **         A working DHCP server was not found on this network.           **"
  puttext "  **    Remote Drive Erase requires a valid IP address and will now halt.   **"
  puttext "  ****************************************************************************"
  while true; do
    :
  done
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
	echo "" >$ttyport
	echo "ECHO %APP_BUILD%" >$ttyport
	read -t 4 BUILD <$ttyport
	if [ $BUILD -gt 122 ]; then
		RIL=1
		input="serial"
		echo "" >$ttyport        
		echo "TERMINAL_SHOW" >$ttyport
		echo "" >$ttyport
#		echo "ECHO %LINK_RENEGOTIATE%" >$ttyport
#		read -t 4 renegotiate <$ttyport
	else
		RIL=0
	fi
else 
	RIL=0
fi
echo `date`" Variable RIL is "$RIL >>/tmp/progress.txt

puttext clear

#Determine if input is coming from local console or remote
if [ "$RIL" != "1" ]; then
	input=`parseparamxml "input"`
	if [ "$input" == "" ]; then
		puttext "  ****************************************************************************"
	  puttext "  **    Remote Drive Erase for PCs featuring Intel(r) vPro(tm) technology   **"
	  puttext "  ****************************************************************************"
		puttext "Press 'c' to continue please"
		temp1=$(getkey)
		input1=`echo "$temp1" | awk '{print $2}'` 
		input=$input1
		puttext clear
	fi
fi
echo `date`" Variable input is "$input >>/tmp/progress.txt
displaymessage

#Obtain server name for smtp
server=`parseparamxml "server"`
if [ "$server" == "" ]; then
	if [ "$RIL" == "1" ]; then
		echo "" >$ttyport
		echo "REQUEST_INPUT Enter SMTP server (FQDN) or click 'X' to not send e-mail" >$ttyport
		read -r server <$ttyport
	else
		puttext "Enter SMTP server (FQDN) or just press enter to not send e-mail "
		server=$(getkeys)
	fi
	#remove ticks and dollars from input
	server=`echo $server | tr -d '\`$'`
fi
echo `date`" Variable server is "$server >>/tmp/progress.txt

#Obtain the port number for smtp server
port=`parseparamxml "port"`
if [ "$port" == "" ] && [ "$server" != "" ]; then
	if [ "$RIL" == "1" ]; then
		echo "" >$ttyport
		echo "REQUEST_INPUT Enter port number (25, 465, 587) for SMTP server" >$ttyport
		read -r port <$ttyport
	else
		puttext "Enter port number (25, 465, 587) for SMTP server "
		port=$(getkeys)
	fi
	#remove ticks and dollars from input
	port=`echo $port | tr -d '\`$'`
fi
echo `date`" Variable port is "$port >>/tmp/progress.txt

#Obtain encryption setting
encryption=`parseparamxml "encryption"`
if [ "$encryption" == "" ] && [ "$server" != "" ]; then
	if [ "$RIL" == "1" ]; then
		echo "" >$ttyport
		echo "REQUEST_INPUT Enter type of encryption (None, SSL, TLS)" >$ttyport
		read -r encryption <$ttyport
	else
		puttext "Enter type of encryption (None, SSL, TLS) "
		encryption=$(getkeys)
	fi
	#remove ticks and dollars from input
	encryption=`echo $encryption | tr -d '\`$'`
fi
encryption=`echo $encryption | tr "[:upper:]" "[:lower:]"`
echo `date`" Variable encryption is "$encryption >>/tmp/progress.txt

#Obtain authentication setting
authentication=`parseparamxml "authentication"`
if [ "$authentication" == "" ] && [ "$server" != "" ]; then
	if [ "$RIL" == "1" ]; then
		echo "" >$ttyport
		echo "REQUEST_INPUT Enter authentication required (Yes, No)" >$ttyport
		read -r authentication <$ttyport
	else
		puttext "Enter authentication required (Yes, No) "
		authentication=$(getkeys)
	fi
	#remove ticks and dollars from input
	authentication=`echo $authentication | tr -d '\`$'`
fi
authentication=`echo $authentication | tr "[:upper:]" "[:lower:]"`
echo `date`" Variable authentication is "$authentication >>/tmp/progress.txt

#Obtain the username for authentication
username=`parseparamxml "username"`
if [ "$username" == "" ] && [ "authentication" == "yes" ]; then
	if [ "$RIL" == "1" ]; then
		echo "" >$ttyport
		echo "REQUEST_INPUT Enter your SMTP username (john@doe.com)" >$ttyport
		read -r username <$ttyport
	else
		puttext "Enter your SMTP username (john@doe.com) "
		username=$(getkeys)
	fi
	#remove ticks and dollars from input
	username=`echo $username | tr -d '\`$'`
fi
echo `date`" Variable username is "$username >>/tmp/progress.txt

#Obtain the password for authentication
password=`parseparamxml "password"`
if [ "$password" == "" ] && [ "authentication" == "yes" ]; then
	if [ "$RIL" == "1" ]; then
		echo "" >$ttyport
		echo "REQUEST_INPUT Enter your SMTP password" >$ttyport
		read -r password <$ttyport
	else
		puttext "Enter your SMTP password "
		password=$(getkeys)
	fi
	#remove ticks and dollars from input
	password=`echo $password | tr -d '\`$'`
fi

#Obtain the recipient
recipient=`parseparamxml "recipient"`
if [ "$recipient" == "" ] && [ "$server" != "" ]; then
	if [ "$RIL" == "1" ]; then
		echo "" >$ttyport
		echo "REQUEST_INPUT Enter the e-mail recipient (jane@doe.com)" >$ttyport
		read -r recipient <$ttyport
	else
		puttext "Enter the e-mail recipient (jane@doe.com) "
		recipient=$(getkeys)
	fi
	#remove ticks and dollars from input
	recipient=`echo $recipient | tr -d '\`$'`
fi
echo `date`" Variable recipient is "$recipient >>/tmp/progress.txt

#Obtain the sender
sender=`parseparamxml "sender"`
if [ "$sender" == "" ] && [ "$server" != "" ]; then
	if [ "$RIL" == "1" ]; then
		echo "" >$ttyport
		echo "REQUEST_INPUT Enter the e-mail sender (john@doe.com)" >$ttyport
		read -r sender <$ttyport
	else
		puttext "Enter the e-mail sender (john@doe.com) "
		sender=$(getkeys)
	fi
	#remove ticks and dollars from input
	sender=`echo $sender | tr -d '\`$'`
fi
echo `date`" Variable sender is "$sender >>/tmp/progress.txt

#Obtain the subject line
subject=`parseparamxml "subject"`
if [ "$subject" == "" ] && [ "$server" != "" ]; then
	if [ "$RIL" == "1" ]; then
		echo "" >$ttyport
		echo "REQUEST_INPUT Enter the e-mail subject line" >$ttyport
		read -r subject <$ttyport
	else
		puttext "Enter the e-mail subject line "
		subject=$(getkeys)
	fi
	#remove ticks and dollars from input
	subject=`echo $subject | tr -d '\`$'`
fi
echo `date`" Variable subject is "$subject >>/tmp/progress.txt

while true; do
  puttext clear
  puttext "  ****************************************************************************"
  puttext "  **    Remote Drive Erase for PCs featuring Intel(r) vPro(tm) technology   **"
  puttext "  **                                                                        **"
  puttext "  **                   Available Disks to Remote Erase                      **"
  puttext "  ****************************************************************************"

	var0=0
	valid=0 
	for match in `fdisk -l`; do
		if [ `echo $match | grep "Disk /dev"` ]; then
			if [ `echo $match | grep "GB,"` ]; then
				valid=1
			elif [ `echo $match | grep "MB,"` ]; then
				valid=0
			fi
		  if [ `echo $match | grep "doesn't contain"` ] && [ $valid -eq 1 ]; then
		    puttext "     "$match
		  elif [ $valid -eq 1 ]; then
		    var0=$((var0 + 1))
		    puttext ""
		    puttext "  "$var0") "$match
		  fi
		elif [ `echo $match | grep "Device Boot"` ] && [ $valid -eq 1 ]; then
		  puttext "     "$match
		elif [ `echo $match | grep "/dev/sd[a-d][1-4]"` ] && [ $valid -eq 1 ]; then
		  puttext "     "$match
		fi
	done

  puttext ""
#  puttext "  Enter Disk Number to Remote Erase or type 'all' for all disks..."
	if [ $var0 -eq 1 ]; then
		puttext "  Press 'Enter' to Remote Erase this Disk..."
		temp_input=$(getkeys)
		disk_input="1"
	else
		puttext "  Enter Disk Number to Remote Erase..."
		disk_input=$(getkeys)
	fi

  disk_id="none"
  if [ `echo $disk_input | grep "^[1-9]"` ]; then
    case $disk_input in
      1) disk_id="sda" ;;
      2) disk_id="sdb" ;;
      3) disk_id="sdc" ;;
      4) disk_id="sdd" ;;
      5) disk_id="sde" ;;
      6) disk_id="sdf" ;;
      7) disk_id="sdg" ;;
      8) disk_id="sdh" ;;
      9) disk_id="sdi"
    esac
#  elif [ `echo $disk_input | grep -i "^[all]"` ]; then
#    disk_id="all"
  fi

  if [ "$disk_id" != "none" ]; then

		for match in `fdisk -l`; do
			if [ `echo $match | grep $disk_id":"` ]; then
				hdsize=`echo $match | grep -o '[0-9].*GB' | grep -o '[0-9].*\.' | grep -o '[0-9].*[0-9]'`
				puttext "clear"
				puttext ""
				low_time=`date -d 00:$(($hdsize/4)) +%H:%M`":00"
				med_time=`date -d 00:$(($hdsize*3/4)) +%H:%M`":00"
				hi_time=`date -d 00:$(($hdsize*7/4)) +%H:%M`":00"
				puttext "  Estimated time (HH:MM:SS) to erase Disk /dev/"$disk_id":"
				puttext "     Low erase level would be "$low_time
				puttext "     Medium erase level would be "$med_time
				puttext "     High erase level would be "$hi_time
				puttext ""
			fi
		done

    puttext "  Type 'low' 'medium' or 'high' exactly to select erase level..."
		level_input=""
    level_input=$(getkeys)
    if [ "$level_input" == "low" ]; then
      before=`date +%s`
      sendemail "Starting a one pass remote erase of Disk /dev/"$disk_id" on "`date`" with an estimated time of "$low_time" ..."
      if [ "$input" == "serial" ]; then
        shred -n0 -z -v /dev/$disk_id &>$ttyport
      else
        shred -n0 -z -v /dev/$disk_id
      fi
      after=`date +%s`
      elapsed=`expr $after - $before`
      sendemail "Finished a one pass remote erase of Disk /dev/"$disk_id" on "`date`" with an elapsed time of "`date -d 00:00:$elapsed +%H:%M:%S`" ..."
      puttext "Erase completed: "`date`
      puttext "Elapsed time: "`date -d 00:00:$elapsed +%H:%M:%S`
      puttext "Press 'Enter' to continue..."
      pause=$(getkeys)
    elif [ "$level_input" == "medium" ]; then
      before=`date +%s`
      sendemail "Starting a three pass remote erase of Disk /dev/"$disk_id" on "`date`" with an estimated time of "$med_time" ..."
      if [ "$input" == "serial" ]; then
        shred -n2 -z -v /dev/$disk_id &>$ttyport
      else
        shred -n2 -z -v /dev/$disk_id
      fi
      after=`date +%s`
      elapsed=`expr $after - $before`
      sendemail "Finished a three pass remote erase of Disk /dev/"$disk_id" on "`date`" with an elapsed time of "`date -d 00:00:$elapsed +%H:%M:%S`" ..."
      puttext "Remote Erase completed: "`date`
      puttext "Elapsed time: "`date -d 00:00:$elapsed +%H:%M:%S`
      puttext "Press 'Enter' to continue..."
      pause=$(getkeys)
    elif [ "$level_input" == "high" ]; then
      before=`date +%s`
      sendemail "Starting a seven pass remote erase of Disk /dev/"$disk_id" on "`date`" with an estimated time of "$hi_time" ..."
      if [ "$input" == "serial" ]; then
        shred -n6 -z -v /dev/$disk_id &>$ttyport
      else
        shred -n6 -z -v /dev/$disk_id
      fi
      after=`date +%s`
      elapsed=`expr $after - $before`
      sendemail "Finished a seven pass remote erase of Disk /dev/"$disk_id" on "`date`" with an elapsed time of "`date -d 00:00:$elapsed +%H:%M:%S`" ..."
      puttext "Remote Erase completed: "`date`
      puttext "Elapsed time: "`date -d 00:00:$elapsed +%H:%M:%S`
      puttext "Press 'Enter' to continue..."
      pause=$(getkeys)
    elif [ "$level_input" == "test" ]; then
      sendemail "Testing of email in Remote Drive Erase on "`date`" ..."
      puttext "Test of email in Remote Drive Erase completed: "`date`
      puttext "Press 'Enter' to continue..."
      pause=$(getkeys)
    elif [ "$level_input" == "logs" ]; then
			var0=0
			puttext "*** progress.txt ***"
			for match in `cat /tmp/progress.txt`; do
				puttext $match
		    var0=$((var0 + 1))
		    if [ $var0 -gt 20 ]; then
				  puttext "Press 'Enter' to continue..."
				  pause=$(getkeys)
				  var0=0
				fi
			done
      puttext "Press 'Enter' to continue..."
      pause=$(getkeys)

			var0=0
			puttext "*** errors.log ***"
			for match in `cat /tmp/errors.log`; do
				puttext $match
		    var0=$((var0 + 1))
		    if [ $var0 -gt 20 ]; then
				  puttext "Press 'Enter' to continue..."
				  pause=$(getkeys)
				  var0=0
				fi
			done
      puttext "Press 'Enter' to continue..."
      pause=$(getkeys)
#    elif [ "$level_input" == "debug" ]; then
#    	break
    fi
  fi
done


