#! /bin/sh
#  ------------------------------------------------------------
#  Company: Software- und Organisations-Service GmbH
#  Purpose: Watchdog script for JS7 Controller
#  ------------------------------------------------------------

set -e
JS7_CONTROLLER_EXIT=0

HTTPS_PORT_OPTION=""
test -z "${JS7_CONTROLLER_HTTPS_PORT}" || HTTPS_PORT_OPTION="--https-port=${JS7_CONTROLLER_HTTPS_PORT}"

start_controller() 
{
  echo "\"${JAVABIN}\" -DJS7.Controller=\"${JS7_CONTROLLER_ID}\" ${JS7_CONTROLLER_JAVA_OPTIONS} -classpath \"${JS7_CONTROLLER_CLASSPATH}\" js7.controller.ControllerMain --id=\"${JS7_CONTROLLER_ID}\" --http-port=\"${JS7_CONTROLLER_HTTP_PORT}\" ${HTTPS_PORT_OPTION} --config-directory=\"${JS7_CONTROLLER_CONFIG_DIR}\" --data-directory=\"${JS7_CONTROLLER_DATA}\""
  "${JAVABIN}" -DJS7.Controller="${JS7_CONTROLLER_ID}" ${JS7_CONTROLLER_JAVA_OPTIONS} -classpath "${JS7_CONTROLLER_CLASSPATH}" js7.controller.ControllerMain --id="${JS7_CONTROLLER_ID}" --http-port="${JS7_CONTROLLER_HTTP_PORT}" ${HTTPS_PORT_OPTION} --config-directory="${JS7_CONTROLLER_CONFIG_DIR}" --data-directory="${JS7_CONTROLLER_DATA}" &
  JS7_CONTROLLER_EXIT=$?
  if [ "${JS7_CONTROLLER_EXIT}" = "0" ]
  then
    create_pid_file $!
    JS7_CONTROLLER_PID=$!
    echo "...JS7 Controller(${JS7_CONTROLLER_ID}) is started with pid=${JS7_CONTROLLER_PID}!"
    echo "...see log file ${JS7_CONTROLLER_LOGS}/controller.log"
    echo "...watchdog for pid ${JS7_CONTROLLER_PID} is started"
    echo "Hit ENTER to return to command prompt."
    wait "${JS7_CONTROLLER_PID}" 2>/dev/null || JS7_CONTROLLER_EXIT=$?
  fi
  
  rm "${JS7_CONTROLLER_PID_FILE}" >/dev/null 2>/dev/null || true
  
  #abort and restart
  if [ "${JS7_CONTROLLER_EXIT}" = "98" ]
  then
    start_controller
  fi
  #terminate and restart
  if [ "${JS7_CONTROLLER_EXIT}" = "97" ]
  then
    start_controller
  fi
  with_revert
}

create_pid_file() 
{
  JS7_CONTROLLER_PID=$1
  echo "${JS7_CONTROLLER_PID}" > "${JS7_CONTROLLER_PID_FILE}" || true
  if [ ! -f "${JS7_CONTROLLER_PID_FILE}" ]
  then
    echo "...could not create pid file: \"${JS7_CONTROLLER_PID_FILE}\""
    echo "...please check permissions for directory: \"${JS7_CONTROLLER_PID_FILE_DIR}\"."
    exit 3
  else
    chmod 666 "${JS7_CONTROLLER_PID_FILE}" 2>/dev/null || true
  fi 
}

with_revert()
{
  if [ -f "${JS7_CONTROLLER_LOGS}/with_revert" ]
  then
    rm -f "${JS7_CONTROLLER_LOGS}/with_revert" 2>/dev/null || true
	export JS7_CONTROLLER_DATA
    "${JAVABIN}" -classpath "${JS7_CONTROLLER_HOME}/lib/classes" RevertClusterInJournal
    exit $?
  fi
}

without_watchdog()
{
  test -z "${JS7_WITHOUT_WATCHDOG}" && return 1
  return "${JS7_WITHOUT_WATCHDOG}"
}

if without_watchdog
then
  start_controller
else
  start_controller > "${JS7_CONTROLLER_LOGS}/watchdog.log" 2>&1
fi

set +e
exit ${JS7_CONTROLLER_EXIT}