#!/bin/bash
# Filename:      ngcp-check-active
# Purpose:       check if running system is an active High Availability node
################################################################################


usage()
{
  # shellcheck disable=SC2088
  echo "$0 - check if system is the active HA node.

Usage:

  -h, --help             display this help text and exit
  -p, --prompt           set output mode to one-character status for prompt inclusion
  -v, --verbose          set output mode to a descriptive status
  -i, --instance <NAME>  instance to check
  -q, --quiet            set output mode to quiet

As usual, the last output mode option overrides any previous ones.

Return codes, prompt and verbose output:

  RC  Prompt  Verbose     Description
  --  ------  -------     -----------
  0   !       active      This is the active HA node.
  1   .       standby     This is NOT the active HA node.
  2   ?       unknown     Error retrieving HA configuration.
"
}

declare -A status_map
status_map=(
  [active]="!"
  [standby]="."
  [unknown]="?"
)

print_status()
{
  local status="$1"

  if [ "${OUTPUT}" = prompt ]; then
    echo "${status_map[$status]}"
  elif [ "${OUTPUT}" = verbose ]; then
    echo "${status}"
  fi
}

OUTPUT=none
INSTANCE=

# Make the interface easier for humans.
if [ -t 1 ]; then
  OUTPUT=verbose
fi

while [ $# -gt 0 ]; do
  case "$1" in
  -p|--prompt)
    OUTPUT=prompt
    ;;
  -v|--verbose)
    OUTPUT=verbose
    ;;
  -q|--quiet)
    OUTPUT=none
    ;;
  -i|--instance)
    shift
    INSTANCE="$1"
    ;;
  -h|--help)
    usage
    exit 0
    ;;
  esac

  shift
done

if [ "${EUID}" != "0" ] ; then
  echo "Error: this script requires root permissions." >&2
  exit 1
fi

if [ -f /etc/default/ngcp-roles ] ; then
  # shellcheck disable=SC1091
  . /etc/default/ngcp-roles
fi

HACRM=$(ngcp-ha-crm)
if [ -n "${INSTANCE}" ] ; then
  if [ "${HACRM}" != "pacemaker" ] ; then
    echo "Error: instances are only supported via pacemaker" >&2
    exit 1
  fi
  CRM_GROUP=g_inst${INSTANCE}_vips
else
  CRM_GROUP=g_vips
fi

case "${HACRM}" in
  pacemaker)
    # We cannot use «grep -q» because crm_mon has an assert on its printing
    # functions, which means that if our caller set SIGPIPE to ignore, then
    # the function will coredump.
    if [ -n "${NGCP_HOSTNAME}" ] && \
      crm_mon -r -1 --output-as=text --resource="${CRM_GROUP}" 2>/dev/null \
        | grep "Started.*${NGCP_HOSTNAME}" >/dev/null; then
      status="active"
    else
      status="standby"
    fi
    ;;
  none)
    # CE
    status="active"
    ;;
  *)
    status="unknown"
    ;;
esac

print_status "${status}"

case "${status}" in
  active)
    exit 0
    ;;
  standby)
    exit 1
    ;;
  *)
    # unknown
    exit 2
    ;;
esac

## END OF FILE #################################################################
