#!/bin/bash
#
# NAME
#     status.sh - Checks the status of the nevisAuth instance.
#
# SYNOPSIS
#     status.sh
#
# DESCRIPTION
#     Performs periodic checks until the instance is up or broken or timeout is reached.
#     The script terminates when the process of the instance stops running.
#     There are no arguments for this script.
#
# EXIT CODES
#  0    Instance is up.
#  1    Instance process is not running.
#  2    Instance is broken.
#  3    Timeout reached.

# Defines how much we should sleep between checking if the instance is up.
interval=1
# Defines how much we should wait the instance to start up until we give up and exit.
timeout=70
((end_time=${SECONDS}+$timeout))

# Checks if the process of the instance is still running.
# Arguments:
#   None
# Returns:
#   In case it is running, returns 0, otherwise non-zero (exit code of systemctl).
isProcessRunning() {
  systemctl is-active --quiet nevisauth@default
  IS_RUNNING=$?
  return $IS_RUNNING
}

# Checks if the instance is up. (Attempts connecting to the instance)
# Arguments:
#   None
# Returns:
#   If the connection was successful and the instance up (is not broken), returns 0.
#   If the connection was not successful, returns 1.
checkInstance() {
  lsof -i :8991 -sTCP:LISTEN
  EXIT_CODE=$?
  return $EXIT_CODE
}

# This function encapsulates the logic of checking if the process is running and if the instance is up.
# In case the process is not running, exits with exit code 1.
# Arguments:
#   None
# Returns:
#   If the instance process is running, returns the result of the instance check function.
check() {
 if isProcessRunning
  then
    checkInstance
    CS=$?
    return $CS
  else
    echo "Process is not running."
    exit 1
  fi
}

# Check the status of the instance periodically.
while ((${SECONDS} < ${end_time}))
do
  sleep ${interval}
  if check
  then
    echo "Instance is up."
    exit 0
  fi
done

echo "Exceeded check timeout (70s). Instance is down."
exit 3