#!/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"`
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
    "TRU64")
      rsh ${HOSTNAM} \
          "/sbin/shutdown -h now && echo 'Shutdown in progress'" >${RSHOUT} 2>&1
      grep -q "^Shutdown in progress$" ${RSHOUT} && RSHOK=1
      ;;
    "VMS")
      rsh -l system ${HOSTNAM} \
          "@SYS\$MANAGER:CHARON_SHUTDOWN" >${RSHOUT} 2>&1
      #--- With some OpenVMS versions, the "RSH was successful" is not returned so
      #--- uncomment the line below and comment the other one
      #grep -q "%RUN-S-PROC_ID" ${RSHOUT} && RSHOK=1
      grep -q "%RUN-S-PROC_ID" ${RSHOUT} && grep -q "RSH was succcessful" ${RSHOUT} && RSHOK=1
      ;;
  esac

  if test ${RSHOK} = 1
  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/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
