#!/bin/bash
# Products: PAR
# 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 -> "HPUX" or "MPEIX"
#
. /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"

PORT=`grep -v ^# $1 | grep -e uart0.device.port -e gsc.lasi.uart.device.port | cut -f2 -d'=' | tr -d ":'\""`
if test -z "${PORT}"
then
  echo "[ERROR] Console port is not correctly defined. Abort."
  exit 1
fi

PID=`ps -ef|grep telnet|grep localhost|grep $PORT|grep -v script|awk '{print \$2}'`
test -n "${PID}" && kill -15 ${PID}
PID=`ps -ef | grep putty | grep "\-P ${PORT}" | awk '{print $2}' | tr "\n" " "`
test -n "${PID}" && kill -15 ${PID}
PID=`ps -ef | grep xhpterm | grep "\-port ${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 not possible otherwise
  PID=`ps -ef | grep -w $2 | grep "\-f $1" | awk '{print $2}'`
  if test -n "${PID}"
  then
    SVC=`basename $1 | sed "s=\.cfg==g"`
    echo "[INFO ] Killing charon_${SVC} service"
    kill_emulator ${PID}
    sleep 2
    systemctl reset-failed charon_${SVC} 
  else
    echo "[INFO ] No process found for '$2' with '-f $1' ..."
  fi
  #--- Logging the emulator stopped in the log file
  get_logfile $1
  echo "`date +%Y%m%d:%H%M%S.%N | cut -c1-22`:exit: 0" >>${LOGF}
  RET=0
else
  #--- Workaround for cases where the "exit" is not reported in the log file thus no stop alert is sent.
  PID=`ps -ef | grep -w $2 | grep "\-f $1" | awk '{print $2}'`
  if test -z "${PID}"
  then
    get_logfile $1
    if test -z "`tail -1 ${LOGF} | grep ':exit:'`"
    then
      #--- Logging the emulator stopped in the log file
      echo "`date +%Y%m%d:%H%M%S.%N | cut -c1-22`:exit: ${RET}" >>${LOGF}
    fi
  fi
fi
kill -15 ${TPID} 2>/dev/null

exit ${RET}
