#!/bin/bash
#
# Make the running system the active High Availability node
#

status=$(/usr/sbin/ngcp-check-active -v)

if [ "$status" = "active" ]; then
  echo "note: node is already active"
  exit 0
fi

HACRM=$(ngcp-ha-crm)
case "${HACRM}" in
  pacemaker)
    if [[ -r /etc/default/ngcp-roles ]]; then
      # shellcheck disable=SC1091
      . /etc/default/ngcp-roles
    fi

    if [[ -z "${NGCP_HOSTNAME}" ]]; then
      echo "error: NGCP_HOSTNAME is not set" >&2
      exit 1
    fi

    if [[ -z "${NGCP_PAIRNAME}" ]]; then
      echo "error: NGCP_PAIRNAME is not set" >&2
      exit 1
    fi

    CRM_GROUP=g_vips_${NGCP_PAIRNAME}
    # determine if we're still running with the legacy name of the resource,
    # which can happen during upgrades
    # TODO: remove this when no longer needed
    if crm_mon -r -1 --output-as=text --resource="${CRM_GROUP}" 2>/dev/null \
        | grep "No resources" >/dev/null; then
      CRM_GROUP=g_vips
    fi

    LIFETIME=PT2M

    /usr/libexec/ngcp-crm-helper <<-CRM
        cib new ngcp-node-state withstatus force
        maintenance off
        resource cleanup ${CRM_GROUP}
        resource move ${CRM_GROUP} ${NGCP_HOSTNAME} ${LIFETIME}
        cib commit
        cib use live
        cib delete ngcp-node-state
CRM
    ;;
esac
