#!/bin/bash

SHARE_DIR=${SHARE_DIR:-/usr/share/ngcp-system-tools/kamcmd}
RUN_DIR=${RUN_DIR:-/run/kamailio}
kamcmd=$(which kamcmd)
cmd=""

if [ -n "$kamcmd" ]; then
  cmd=$kamcmd
else
  echo "error: kamcmd not found" >&2
  exit 1
fi

if [ -z "${NGCP_KAMCMD_SUPERVISED}" ]; then
  export NGCP_KAMCMD_SUPERVISED=1
  exec timeout -k 2 2 "$0" "$@"
fi

if [ -z "$1" ]; then
  echo "Usage: $0 [lb|proxy|lb-instancename|proxy-instancename] <command>" >&2
  exit 1
fi

target=$1; shift
if [[ "${target}" != "proxy" ]] && [[ "${target}" != "proxy-"* ]] && [[ "${target}" != "lb" ]] && [[ "${target}" != "lb-"* ]]; then
  echo "Usage: $0 [lb|proxy|lb-instancename|proxy-instancename] <command>" >&2
  exit 1
fi

target=${target/-/.}
socket="${RUN_DIR}/ctl.${target}.sock"

export CMD="$cmd -s ${socket}"

action=$1
if [ -f "${SHARE_DIR}/${action}" ] ; then
  shift
  # shellcheck disable=SC1090
  "${SHARE_DIR}/${action}" "$@"
else
  if [ ! -e "${socket}" ]; then
	  echo "Socket file '${socket}' not found, please check the target service or instance"
	  exit 1
  fi
  ${CMD} "$@"
fi
