#!/bin/sh
# P1: contains name of the cfg file, full path
# P2: contains emulator exe file, full path
# P3: guest user
# P4: guest password
# P5: guest prompt
# P6: guest OS type -> "vms" or "tru64"
#
. /opt/charon/utils/charon_common

EXPUSR=$3
EXPPWD=$4
EXPPRT="$5"
OS=`echo $6| tr [:lower:] [:upper:]`
test "${OS}" = "TRU64" && OS="UNIX"

LOGDAT=`date +"%Y%m%d%H%M%S"`
echo "[INFO ] Initiating ${HOSTNAM} system shutdown via EXPECT"

#--- Killing active connection to console if any
echo "[INFO ] Killing active connection to console if any"


CHK=`grep -v ^# $1 | grep -w load | grep -w virtual_serial_line | grep OPA`
if test -z "${CHK}"
then
  INSBLD=`rpm -q charon-license 2>/dev/null | cut -f4 -d'-' | cut -f1 -d'.'`
  INSBLD=${INSBLD:-0}
  test ${INSBLD} -ge 19103 && CHK=`grep -v ^# $1 | grep -w set | grep -w OPA0 | grep -w port`
fi          
PORT=`echo ${CHK} | sed "s/[ \t]\{1,\}/ /g" | sed "s/ =/=/g" | sed "s/= /=/g" | sed "s=\(^.*port\=\)\([0-9]\{1,\}\)\(.*$\)=\2=g"`
if test -z "${PORT}"
then
  echo "[ERROR] OPA0 console port is not correctly defined. Abort."
  exit 1
fi

#---  Killing telnet session on OPA0 if any (on the localhost)
PID=`ps -ef|grep telnet|grep localhost|grep $PORT|grep -v script|awk '{print $2}'`
test -n "${PID}" && kill -15 ${PID}

#---  Killing putty session on OPA0 if any (on the localhost)
PID=`ps -ef | grep putty | grep "\-P ${PORT}" | awk '{print $2}' | tr "\n" " "`
test -n "${PID}" && kill -15 ${PID}

#--- Executing the expect script:
echo "[INFO ] Executing the expect script"
EXPOUT=/opt/charon/log/console.stop.`basename $1|sed "s=\.cfg==g"`.${LOGDAT}.log
touch ${EXPOUT}
tail -Fn0 ${EXPOUT} &
TPID=$!
trap 'kill -15 ${TPID} 2>/dev/null;exit' 1 2 9 14 15

/opt/charon/utils/guest_shutdown.exp ${PORT} ${EXPUSR} ${EXPPWD} "${EXPPRT}" ${OS} >>${EXPOUT} 2>&1
RET=$?
if test ${RET} = 9
then
  #--- Killing the emulator if stop_on=F6 is not set (no 'power off' command for VAX)
  PID=`ps -ef|grep "$2 -d $1"|grep -v grep|awk '{print $2}'`
  if test -n "${PID}"
  then
    kill_emulator ${PID}
    sleep 2
    SVC=`basename $1 | sed "s=\.cfg==g"`
    systemctl reset-failed charon_${SVC} 
  fi
  #--- Logging the emulator stopped in the log file
  get_logfile $1
  echo "`date +'%Y%m%d:%H%M%S'`:INFO :0:Emulator stopped at `date`" >>${LOGF}
  RET=0
fi
kill -15 ${TPID} 2>/dev/null

exit ${RET}