#! /usr/bin/env bash

# Define endpoint
endpoint_url="https://kitcreator.rkeene.org/kitcreator"

# Help
function print_help() {
	echo 'download-api-client [--platform <platform>] [--tcl-version <version>]'
	echo '                    [--kitcreator-version <version>] [--kitdll]'
	echo '                    [--threaded] [--debug] [--dynamictk]'
	echo '                    [--staticpkgs] [--verbose] [--pkg-<package>...]'
	echo '                    [--opt-<option>...] [--empty-packages]'
	echo 'download-api-client {--help|--platforms|--tcl-versions|'
	echo '                     --kitcreator-versions|--packages|'
	echo '                     --options}'
}

# Set arguments
declare -A jsonArgs
jsonArgs["platform"]="$(uname -s)-$(uname -m)"

nextArg=''
kit_filename=''
options=()
packages=()
internalOptionsVerbose='false'
noPackages='false'
downloadSDK='false'
for arg in "$@"; do
	if [ -n "${nextArg}" ]; then
		jsonArgs["${nextArg}"]="${arg}"
		nextArg=''
		continue
	fi

	case "${arg}" in
		--verbose)
			internalOptionsVerbose='true'
			;;
		--platform|--tcl-version|--kitcreator-version)
			nextArg="${arg:2}"
			nextArg="${nextArg//-/_}"
			;;
		--kitdll|--threaded|--debug|--dynamictk|--staticpkgs)
			options+=("${arg:2}")
			;;
		--sdk)
			downloadSDK='true'
			;;
		--opt-*)
			options+=("${arg:6}")
			;;
		--pkg-*)
			packages+=("${arg:6}")
			noPackages='false'
			;;
		--empty-packages)
			packages=()
			noPackages='true'
			;;
		--platforms|--tcl-versions|--kitcreator-versions|--packages|--options)
			action="${arg:2}"
			action="${action//-/_}"

			formatString='%-20s | %s\n'
			printf "${formatString}" Name Description
			printf '%s+%s\n' --------------------- ---------------------
			curl -sSL -d "json={\"action\":\"${action}\"}" "${endpoint_url}" | jq -crM 'keys[] as $k | "\($k) \(.[$k])"' | while read -r platform description; do
				printf "${formatString}" "${platform}" "${description}"
			done
			exit 0
			;;
		--help)
			print_help
			exit 0
			;;
		*)
			echo "Invalid option \"${arg}\"" >&2
			print_help >&2
			exit 1
	esac
done

if [ -n "${options[*]}" ]; then
	jsonArgs["options"]="${options[*]}"
fi

if [ -n "${packages[*]}" -o "${noPackages}" = 'true' ]; then
	jsonArgs["packages"]="${packages[*]}"
fi

# Convert arguments into a request
jqArgs=()
jqSettings=''
for jsonArg in "${!jsonArgs[@]}"; do
	case "${jsonArg}" in
		options|packages)
			requestArray='[]'
			for value in ${jsonArgs[${jsonArg}]}; do
				requestArray="$(jq -crM --arg value "${value}" '. + [ $value ]' <<<"${requestArray}")"
			done
			jqArgs+=(--argjson "${jsonArg}" "${requestArray}")
			;;
		*)
			jqArgs+=(--arg "${jsonArg}" "${jsonArgs[${jsonArg}]}")
			;;
	esac

	jqSettings="${jqSettings} | .${jsonArg} = \$${jsonArg}"
done
jqArgs+=("${jqSettings:3}")

jsonRequest="$(jq -crM "${jqArgs[@]}" <<<'{"action":"build"}')"

# Make the request
results="$(curl -sSL -d "json=${jsonRequest}" "${endpoint_url}")"
url="$(jq -crM .url <<<"${results}")"
while true; do
	info="$(curl -sSL "${url}")"
	terminal="$(jq -crM .terminal <<<"${info}")"

	if [ "${terminal}" = 'true' ]; then
		break
	fi

	if [ -z "${buildStatusWroteHeader}" ]; then
		buildStatusWroteHeader='1'
		echo -n 'Building...'
	fi

	sleep 30

	echo -n '.'
done
status="$(jq -crM .status <<<"${info}")"
build_log_url="$(jq -crM .build_log_url <<<"${info}")"

if [ -n "${buildStatusWroteHeader}" ]; then
	echo " ${status}"
fi

if [ "${status}" != "complete" ]; then
	echo "${status}: Build terminated in error" >&2
	if [ "${internalOptionsVerbose}" = 'true' ]; then
		curl -sSL "${build_log_url}" >&2
	fi

	exit 1
fi

if [ "${downloadSDK}" = 'false' ]; then
	kit_url="$(jq -crM .kit_url <<<"${info}")"
	if [ -z "${kit_filename}" ]; then
		kit_filename="${kit_url//*\//}"
		case "${kit_filename}" in
			*.*)
				kit_filename_base="${kit_filename//.*/}"
				kit_filename_ext=".${kit_filename//*./}"
				;;
			*)
				kit_filename_base="${kit_filename}"
				kit_filename_ext=''
				;;
		esac
		kit_filename_platform="$(jq -crM .platform <<<"${info}")"
		kit_filename_tcl_version="$(jq -crM .tcl_version <<<"${info}")"
		kit_filename="${kit_filename_base}-${kit_filename_platform}-${kit_filename_tcl_version}${kit_filename_ext}"
	fi

	curl -sSL "${kit_url}" > "${kit_filename}"
	chmod 755 "${kit_filename}"
else
	kit_sdk_url="$(jq -crM .kit_sdk_url <<<"${info}")"
	if [ -z "${kit_filename}" ]; then
		kit_filename="${kit_sdk_url//*\//}"
	fi

	curl -sSL "${kit_sdk_url}" > "${kit_filename}"
fi

echo "Wrote: ${kit_filename}"
exit 0
