#!/bin/bash
#
# NGCP Redis connection helper.
#

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

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

usage() {
  echo "Usage: $0 <option>... <location> [<cli-option>...]"
  echo "Options:"
  echo "  -h, --help     display this help message"
  echo "  local          connect to local Redis"
  echo "  ha             connect to central Redis HA"
  echo ""
  echo "The <cli-options> get passed as is to the CLI tool."
  echo ""
  echo "Default: automatically select either local or ha"
  echo ""
  exit 0
}

CLI="/usr/bin/redis-cli"
if [ "${REDIS_FLAVOR:-valkey}" == "valkey" ]; then
  CLI="/usr/bin/valkey-cli"
fi

if [ -n "$1" ]; then
  case "$1" in
  -h | --help)
    usage
    ;;
  local | ha)
    LOCATION="$1"
    ;;
  *)
    echo "Error: unknown Redis location '$1'" >&2
    exit 2
    ;;
  esac
  shift
else
  if [ "${NGCP_IS_MULTI_SITE}" == "yes" ] && [ "${NGCP_IS_DB}" == "yes" ]; then
    LOCATION="ha"
  else
    LOCATION="local"
  fi
fi

case "${LOCATION}" in
local)
  HOST="${LOCAL_REDIS}"
  PORT="${REDIS_PORT}"
  ;;
ha)
  HOST="${CENTRAL_REDIS}"
  PORT="${CENTRAL_REDIS_PORT}"
  ;;
esac

if [ -z "$*" ]; then
  echo "Connecting to Redis ($LOCATION)..."
fi
"${CLI}" -h "${HOST}" -p "${PORT}" "$@"
