#! /usr/bin/env bash

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

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

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

	case "${arg}" in
		--platform|--tcl-version|--kitcreator-version)
			nextArg="${arg:2}"
			nextArg="${nextArg//-/_}"
			;;
		--kitdll|--threaded)
			options+=("${arg:2}")
			;;
	esac
done

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

# Convert arguments into a request
jqArgs=()
jqSettings=''
for jsonArg in "${!jsonArgs[@]}"; do
	case "${jsonArg}" in
		options)
			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}")"

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

if [ "${status}" != "complete" ]; then
	echo "failed: ${status}" >&2

	exit 1
fi

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}"

echo "Wrote: ${kit_filename}"
exit 0
