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

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

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

help() {
  echo "Usage: $0 [-h|--help|local|ha]"
  echo "Options:"
  echo "  -h, --help     display this help message"
  echo "  local          connect to local Redis"
  echo "  ha             connect to central Redis HA"
  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
    if [ "$1" == "-h" ] || [ "$1" == "--help" ]; then
        help
    fi
    if [ "$1" == "local" ]; then
        echo "Connecting to local Redis ..."
        "${CLI}" -h "${LOCAL_REDIS}" -p "${REDIS_PORT}"
    fi
    if [ "$1" == "ha" ]; then
        echo "Connecting to Redis HA ..."
        "${CLI}" -h "${CENTRAL_REDIS}" -p "${CENTRAL_REDIS_PORT}"
    fi
else
    if [ "${NGCP_IS_MULTI_SITE}" == "yes" ] && [ "${NGCP_IS_DB}" == "yes" ]; then
        echo "Connecting to Redis HA ..."
        "${CLI}" -h "${CENTRAL_REDIS}" -p "${CENTRAL_REDIS_PORT}"
    else
        echo "Connecting to local Redis ..."
        "${CLI}" -h "${LOCAL_REDIS}" -p "${REDIS_PORT}"
    fi
fi

