#!/bin/bash
# Sipwise NGCP helper to execute an xmlrpc command to all proxy or lb kamailio services/instances

if [ ! -f /etc/ngcp-provisioning-tools/mysql_values.cfg ]; then
  echo "Missing configuration file /etc/ngcp-provisioning-tools/mysql_values.cfg" >&2
  exit 1
fi
# shellcheck disable=SC1091
. /etc/ngcp-provisioning-tools/mysql_values.cfg

debug () {
  if "$DEBUG" ; then
    echo "[ngcp-kam-parallel-xmlrpc]: $*"
  fi
}

usage () {
  echo " "
  echo "$0 - Script to execute one or more xmlrpc command to all the proxy or lb kamailio services/instances."
  echo " "
  echo "Usage: $0 [-s <service>] <command> [additional_commands]"
  echo " "
  echo "Option:
            -h: Print this help
            -s: Service where to send the xmlrpc commands
                One between 'proxy' or 'lb'. If not specified 'proxy' will be used.
            -v: Verbose mode"
}

# defaults
service="proxy"
DEBUG=${DEBUG:-false}

# wrapper opts
while getopts s:vh name
do
  case "$name" in
    s) service="$OPTARG";;
    v) DEBUG=true;;
    h) usage; exit 0;;
    *)
      usage
      exit 1
      ;;
  esac
done
shift $((OPTIND - 1))

if [[ $# -lt 1 ]] ; then
  echo "At least one command has to be provided"
  usage 2>&1
  exit 1
fi

case "${service}" in
  proxy) xmlrpc_dest=${PRXRPCADDR};;
  lb) xmlrpc_dest=${LBRPCADDR};;
  *) echo "Service must be 'proxy' or 'lb'"
     usage 2>&1
     exit 1
     ;;
esac
debug "Service selected '${service}' with list of IPs '${xmlrpc_dest}'"

for ip in ${xmlrpc_dest}; do
  kamailio_connection="http://${ip}:${KAMAILIO_PROXY_PORT}/"
  for command in "$@"; do
    debug "Executing xmlrpc command '$command' on kamailio service/instance at '${ip}:${KAMAILIO_PROXY_PORT}'"
    curl --connect-timeout 2 \
         -d "<?xml version='1.0'?><methodCall><methodName>$command</methodName></methodCall>" \
         "${kamailio_connection}" >/dev/null 2>&1
  done
done

