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

HOSTNAM=$3
OS=`echo $4 | tr [:lower:] [:upper:]`

LOGDAT=`date +"%Y%m%d%H%M%S"`
SSHOUT=/opt/charon/log/console.stop.`basename $1|sed "s=\.cfg==g"`.${LOGDAT}.log
echo "[INFO ] Initiating ${HOSTNAM} system shutdown via SSH"

ping -c5 ${HOSTNAM} >/dev/null 2>&1
if test $? = 0
then
  echo "[INFO ] ${HOSTNAM} is alive (responds to ping)."
  echo "[INFO ] Initiating system shutdown"

  case "${OS}"
  in
    "TRU64")
      ssh -o ServerAliveInterval=10 -o ServerAliveCountMax=1 -o ConnectTimeout=10 ${HOSTNAM} \
          "/sbin/shutdown -h now" >${SSHOUT} 2>&1
      ;;
    "VMS")
      ssh -o ServerAliveInterval=10 -o ServerAliveCountMax=1 -o ConnectTimeout=10 system@${HOSTNAM} \
          "@SYS\$MANAGER:CHARON_SHUTDOWN" >${SSHOUT} 2>&1
      ;;
  esac

  echo "[INFO ] Waiting for shutdown completion..."
  while test 1
  do
    ping -c2 ${HOSTNAM} >/dev/null 2>&1
    #--- Break if the system is no more responding
    test $? = 0 || break
    echo "[INFO ] ${HOSTNAM} still responds to ping..."
    sleep 5
  done
  echo "[INFO ] ${HOSTNAM} does not respond to ping anymore."
  sleep 10
else
  echo "[WARN ] ${OS} system ${HOSTNAM} is not alive."
fi

#--- Killing/stopping the emulator
PID=`ps -ef|grep "$2 -d $1"|grep -v grep|awk '{print $2}'`
if test -z "${PID}"
then
  echo "[INFO ] Emulator is stopped"
else
  SVC=`basename $1 | sed "s=\.cfg==g"`
  echo "[INFO ] Killing charon_${SVC} service"
  kill_emulator ${PID}
  sleep 2
  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}

exit 0
