#!/bin/bash
#
#  Copyright (c) 2020, Oracle and/or its affiliates.
#

#
# Lists the members of SGD array(s) on the gateway.
#

. "${INSTDIR}/bin/scripts/common"

: ${trace:=""}
[ "${trace}" = "x" ] && set -x

OUTPUT_DIR="${INSTDIR}/proxy/var/info"
ARRAYS="${OUTPUT_DIR}/arrays"

#
# Checks if the Gateway has any arrays configured, if not a message is displayed
# and the script will exit.
#
checkArrayIsConfigured() {
	if [[ ! -s "${ARRAYS}" ]]; then
		echo "${i18n_error_gatewaylistarray_no_arrays_configured}"
		exit 0
	fi
}

#
# Print a specified array and its members to the command line.
#
# @param $1  A line from the "$ARRAYS" file representing the array to print.
#
# @param $2  (optional)  A name to verify $1 against, if this does not match the array name
#            in $1 it is an error.
#
printSpecificArray() {

	line="$1"
	named_array="$2"

	# extract the name & array nodes from the line
	array_name=$(echo "${line}" | cut -d'=' -f1 | tr --delete " ")
	array_nodes=$(echo "${line}" | cut -d'=' -f2-)

	# if we are printing a named array - make sure we actually matched the array
    # name & not a member on the same line in the "$ARRAYS" file
	if [ -n "${named_array}" -a "$named_array" != "$array_name" ]
	then
		echo "${i18n_error_gatewaylistarray_named_gateway_not_listed} \n"
		exit 1
	fi

	# print the array name
	printf "\n"
	printf " > ${array_name}\n"
	printf " ------------------------------\n"

	# since $array_nodes are space separated we can treat them like an array
	for i in ${array_nodes[@]}
	do
		# print the name of each node
		printf " * $i \n"
	done
}

#
# Print all the listed arrays in the "$ARRAYS" file.
#
printAllArrays() {
    # read the $ARRAYS file line by line
	# check $line is not empty to prevent last line being ignored
	# as read will return a non-zero exit code when it encounters EOF
	while read -r line || [ -n "$line" ]
	do
		printSpecificArray "$line"
	done < "$ARRAYS"
	printf " \n"
}

#
# Entry point for "gateway server list-array" command
#
server_list_array() {
	if [ $# -eq 0 ]
	then
		checkArrayIsConfigured
		printAllArrays
		exit 0
	fi

	case "$1" in
	--help)
		echo "${i18n_gatewaylistarray_longusage_gw}"
        exit 1
		;;

	--name)
		if [ $# -lt 2 ]
		then
			echo "${i18n_error_gatewaylistarray_no_name_given}"
			exit 1
		fi

		checkArrayIsConfigured

		arg_name="$2"
		array_line=$(grep --max-count=1 --word-regexp "${arg_name}" "${ARRAYS}")

		if [ -z "${array_line}" ]
		then
			echo "${i18n_error_gatewaylistarray_named_gateway_not_listed}"
			exit 1
		fi

		printSpecificArray "${array_line}" "${arg_name}"
		exit 0
		;;

	*)
		printf "${i18n_badarg01_gw}" "$1"
		echo "${i18n_gatewaylistarray_shortusage_gw}"
        exit 1
		;;
	esac
}
