#!/bin/bash

set -e

SELF="${0##*/}"

usage()
{
  echo "Usage: $SELF [<option>] [<hostname>]

Options:
  -h, --help    display this help text and exit
  -q, --quiet   set output mode to quiet

<hostname> defaults to 'localhost' if not specified.

Return codes and verbose output:

  RC  Verbose     Description
  --  -------     -----------
  0   up          The HA host is up.
  1   down        The HA host is down.
  2   unknown     Error retrieving HA host state.
"
}

state()
{
  if [ "${OUTPUT}" = 'verbose' ]; then
    echo "$2"
  fi
  exit "$1"
}

up()
{
  state 0 up
}

down()
{
  state 1 down
}

unknown()
{
  state 2 unknown
}

OUTPUT=verbose

while [ $# -gt 0 ]; do
  case "$1" in
  -q|--quiet)
    OUTPUT=none
    ;;
  -h|--help)
    usage
    exit 0
    ;;
  *)
    break
    ;;
  esac

  shift
done

HACRM="$(ngcp-ha-crm)"
nodeself="$(ngcp-hostname)"
node="${1:-${nodeself}}"

case "${HACRM}" in
  none)
    if [ "${node}" = "${nodeself}" ]; then
      up
    else
      unknown
    fi
    ;;
  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 crm_mon -1 --output-as=text | grep "Online: .*${node}" >/dev/null; then
      up
    else
      down
    fi
    ;;
  *)
    unknown
    ;;
esac
