#!/bin/bash

ZKCLI="${ZKCLI:-"/usbkey/scripts/zookeepercli"}"
CURL="${CURL:-"/opt/local/bin/curl"}"
JSON="${JSON:-"/usr/bin/json"}"
PYTHON="${PYTHON:-"/opt/local/bin/python"}"
USE_CURL=1
HTTP_SCHEME="https"
HTTP_PORT="12181"
ACTION_PARAMS=()
ZK_FORCE=""
ZK_USERNAME="esdc"
CFGDB_HOSTNAME="esdc.local"

usage() {
	echo "Usage:   $0 [--legacy|--no-ssl|--force|-k] <command/query>"
	echo "Example: $0 ls /esdc/nodes"
}

while true; do
	case "$1" in
		--help|-h)
			usage
			exit 0
			;;
		--old|--legacy)
			USE_CURL=""
			shift
			;;
		--no-ssl|--no-tls)
			HTTP_SCHEME="http"
			shift
			;;
		--force)
			ZK_FORCE="true"
			shift
			;;
		-*)
			ACTION_PARAMS+=("$1")
			shift
			;;
		*)
			QUERY_STRING=("${@}")
			break
			;;
	esac
done


if [[ "${#QUERY_STRING[@]}" -le 1 ]]; then
	usage 1>&2
	exit 10
fi

if [[ -n "${USE_CURL}" ]]; then
	if [[ ! -x "${CURL}" ]]; then
		echo "ERROR: Cannot find binary ${CURL}" 1>&2
		exit 20
	fi
else
	if [[ ! -x "${ZKCLI}" ]]; then
		echo "ERROR: Cannot find binary ${ZKCLI}" 1>&2
		exit 20
	fi
fi

# find and load config file (usually /usbkey/config)
# shellcheck disable=SC1091
. /lib/sdc/config.sh
load_sdc_config

#shellcheck disable=SC2154
ZK_IP="${CONFIG_cfgdb_admin_ip}"
#shellcheck disable=SC2154
ZK_PASSWORD="${CONFIG_esdc_install_password}"

if [[ -z "${ZK_IP}" ]]; then
	echo "ERROR: Missing cfgdb_admin_ip in config file" 1>&2
	exit 31
fi

if [[ -z "${ZK_PASSWORD}" ]]; then
	echo "ERROR: Missing esdc_install_password in config file" 1>&2
	exit 32
fi

if [[ -z "${USE_CURL}" ]]; then
	# Legacy zookeepercli
	"${ZKCLI}" -servers "${ZK_IP}" -auth_usr "${ZK_USERNAME}" -auth_pwd "${ZK_PASSWORD}" "${ACTION_PARAMS[@]}" -c "${QUERY_STRING[@]}"
	exit $?
fi

ZK_CMD="${QUERY_STRING[0]}"
ZK_NODE="${QUERY_STRING[1]}"
unset -v 'QUERY_STRING[0]'
unset -v 'QUERY_STRING[1]'
ZK_DATA="${QUERY_STRING[*]}"

# For SSL connection we need to connect to $CFGDB_HOSTNAME because the certificate is valid only for this name
if [[ "${HTTP_SCHEME}" == "https" ]]; then
	if [[ "${ZK_IP}" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
		ip="${ZK_IP}"
	else
		ip="$(getent hosts "${ZK_IP}" | awk '{ print $1 ; exit }')"
	fi

	if [[ -n "${ip}" ]]; then
		ACTION_PARAMS+=("--resolve" "${CFGDB_HOSTNAME}:${HTTP_PORT}:${ZK_IP}")
		ZK_IP="${CFGDB_HOSTNAME}"
	fi
fi

URL="${HTTP_SCHEME}://${ZK_IP}:${HTTP_PORT}${ZK_NODE}?cmd=${ZK_CMD}"

# Create json object with "data" and/or "force" attributes
if [[ -n "${ZK_DATA}" ]]; then
	stringified_json_data="$(printf '%s' "${ZK_DATA}" | "${PYTHON}" -c 'import json,sys; print(json.dumps(sys.stdin.read()))')"
	json_data="{\"data\":${stringified_json_data}}"
else
	json_data="{}"
fi

if [[ -n "${ZK_FORCE}" ]]; then
	json_data="$(echo "${json_data}{\"force\":true}" | "${JSON}" --merge -o json-0)"
fi

if [[ "${json_data}" != "{}" ]]; then
	ACTION_PARAMS+=("--data" "${json_data}")
fi

# Here we go
out=$("${CURL}" -s -S -X PUT -H "zk-username:${ZK_USERNAME}" -H "zk-password:${ZK_PASSWORD}" "${ACTION_PARAMS[@]}" "${URL}" 2>&1)
rc_curl="$?"

# Check for curl errors first
if [[ "${rc_curl}" -ne 0 ]] && [[ "${rc_curl}" -ne 56 ]]; then
	echo "${out}" 1>&2
	exit "${rc_curl}"
elif [[ "${rc_curl}" -eq 56 ]]; then
	# workaround openssl 1.1.1e bug in pkgsrc 2020Q1
	# https://help.whmcs.com/m/troubleshooting/l/1230985-troubleshooting-curl-error-56-openssl-ssl_read-unexpected-eof-while-reading
	out="$(echo "${out}" | grep -v '^curl: (56)')"
fi

# Output must be in JSON format
rc="$(echo "${out}" | "${JSON}" "returncode" 2> /dev/null)"

# shellcheck disable=SC2181
if [[ "$?" -ne 0 || -z "${rc}" ]]; then
	# Invalid JSON output - probably some error
	echo "${out}" 1>&2
	exit 1
fi

echo "${out}" | "${JSON}" "stdout"
echo "${out}" | "${JSON}" "stderr" 1>&2
exit "${rc}"
