#!/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"`
RSHOUT=/opt/charon/log/console.stop.`basename $1|sed "s=\.cfg==g"`.${LOGDAT}.log
echo "[INFO ] Initiating ${HOSTNAM} system shutdown via RSH"

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

  RSHOK=0
  case "${OS}"
  in
    "HPUX")
      rsh ${HOSTNAM} "/sbin/init 0" >${RSHOUT} 2>&1
      RSHOK=$?
      ;;
  esac

  if test ${RSHOK} = 0
  then
    echo "[INFO ] Success. Now waiting for shutdown completion..."
    sleep 5
    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
    if test -n "`grep 'poll: protocol failure in circuit setup' ${RSHOUT}`"
    then
      echo "[ERROR] Returned 'poll: protocol failure in circuit setup'"
      echo "[ERROR] Please check ports 1011-1023 are opened/firewall"
    fi
    echo "[ERROR] Shutdown procedure failed."
    exit 1
  fi
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
