#!/bin/bash
# Products: PAR
# 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 -> "HPUX"
#
. /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
    "HPUX")
      ssh -o ServerAliveInterval=10 -o ServerAliveCountMax=1 -o ConnectTimeout=10 ${HOSTNAM} \
          "/sbin/init 0" >${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 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}

exit 0
