#!/bin/bash

set -e

check_lb=false
check_proxy=false
service="/usr/sbin/kamailio"
red='\033[0;31m'
nocolor='\033[0m' # No Color

# ---- pre-checks ----
if ! [ -r /etc/default/ngcp-roles ] ; then
  echo "Warning: cannot read /etc/default/ngcp-roles" >&2
  exit 1
fi

# shellcheck disable=SC1091
. /etc/default/ngcp-roles

if [ "$NGCP_IS_LB" = "yes" ]; then
  check_lb=true
fi

if [ "$NGCP_IS_PROXY" = "yes" ]; then
  check_proxy=true
fi

# ---- Setting variables ----
COMPONENT=$1
shm=$(ngcpcfg get "kamailio.${COMPONENT}.shm_mem")
pkg=$(ngcpcfg get "kamailio.${COMPONENT}.pkg_mem")
pid="kamailio.${COMPONENT}.pid"
config="/etc/kamailio/${COMPONENT}/kamailio.cfg"
localnode=$(hostname)

# ---- functions definition ----
usage() {
  echo "Usage: $0 <ngcp-component>

Usage example: $0 lb

  ngcp-component:
    lb              check kamailio config for lb
    proxy           check kamailio config for proxy"
}

check_config() {

  if ! /usr/sbin/ngcp-check-active -q ; then
    echo -e "${red}WARNING: You are not on the ACTIVE node. Checking anyway...${nocolor}"
  fi

  cmd="${service} -c -P /run/kamailio/${pid} -f ${config} -m ${shm} -M ${pkg} -DD"
  ${cmd}
}

#---- main ----
case "$COMPONENT" in
  lb)
    if "${check_lb}" ; then
      check_config
    else
      echo "FAILED: You are trying to check kamailio ${COMPONENT} config from ${localnode} node."
      echo "        Please run the command from a ${COMPONENT} server."
      exit 1
    fi
    exit 0
    ;;
  proxy)
    if "${check_proxy}" ; then
      check_config
    else
      echo "FAILED: You are trying to check kamailio ${COMPONENT} config from ${localnode} node."
      echo "        Please run the command from a ${COMPONENT} server."
      exit 1
    fi
    exit 0
    ;;
  *)
    usage
    exit 1
esac
