#!/bin/sh
# Copyright (c) 2000-2015 Synology Inc. All rights reserved.

. /etc.defaults/rc.subr

ETCD_ERR_UNKNOWN=32

send_curl_dump()
{
	protocal="$1"
	authparams="$2"

	keys=`curl -s ${authparams} ${protocal}://127.0.0.1:2379/v2/keys?quorum=false\&recursive=true \
		| jq -r '.. | objects | if true == .dir then .key=(.key + "/") else . end | select(null != .key?) | .key? ' \
		| grep -v 'syno/live_cluster/log' | sort`

	for key in $keys; do
		local last_char_pos=$((${#key} - 1))
		local value=
		if [ "/" == "${key:$last_char_pos:1}" ]; then
			printf "%-110s\n" $key
		else
			value="`curl -s ${authparams} ${protocal}://127.0.0.1:2379/v2/keys${key} 2>&1 | jq '.node.value'`"
			printf "%-110s := %s\n" "$key" "$value"
		fi
	done
}

etcd_dump()
{
	send_curl_dump "http" ""
}

etcd_auth_dump()
{
	capath="$1"
	crtpath="$2"
	keypath="$3"

	if [ ! -f $capath ]; then
		printf "capath: [%s] not exist\n" "$capath"
		exit 1
	fi

	if [ ! -f $capath ]; then
		printf "crtpath: [%s] not exist\n" "$crtpath"
		exit 1
	fi

	if [ ! -f $capath ]; then
		printf "keypath: [%s] not exist\n" "$keypath"
		exit 1
	fi

	printf "capath: %s\n" "$capath"
	printf "crtpath: %s\n" "$crtpath"
	printf "keypath: %s\n" "$keypath"

	send_curl_dump "https" "-k --cacert $capath --cert $crtpath --key $keypath"
}

tool_name=$0
action=$1; shift
case "$action" in
	dump)
		etcd_dump
		;;
	auth_dump)
		etcd_auth_dump $1 $2 $3
		;;
	*)
		logger -s -p err "${tool_name}: Error: wrong parameters: $action"
		exit $ETCD_ERR_UNKNOWN
		;;
esac

exit $?
# vim:ft=sh
