#!/usr/bin/env bash
set -euo pipefail

readonly ndk_version="${HT_ANDROID_NDK_VERSION:-27.3.13750724}"
readonly cmake_version="${HT_ANDROID_CMAKE_VERSION:-3.22.1}"
readonly cmake_package="cmake-${cmake_version}-linux.zip"
readonly cmake_url="https://dl.google.com/android/repository/${cmake_package}"
readonly cmake_sha256="9196644852a978012caf7a4067ba1898debf6cc204c3341562771e31080d6869"

readonly repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
readonly sdk_root="${ANDROID_SDK_ROOT:-${ANDROID_HOME:-}}"
readonly gradle_home="${GRADLE_USER_HOME:-$repo_root/.gradle}"
readonly download_dir="$gradle_home/android-toolchain-downloads"
readonly archive="$download_dir/$cmake_package"
readonly cmake_dir="$sdk_root/cmake/$cmake_version"
readonly ndk_properties="$sdk_root/ndk/$ndk_version/source.properties"

if [[ -z "$sdk_root" ]]; then
	echo >&2 "ANDROID_SDK_ROOT or ANDROID_HOME must identify the Android SDK."
	exit 1
fi

if [[ ! -f "$ndk_properties" ]] ||
	! grep -Fqx "Pkg.Revision = $ndk_version" "$ndk_properties"; then
	echo >&2 "Android NDK $ndk_version is not installed in $sdk_root."
	exit 1
fi

cmake_is_ready() {
	[[ -x "$cmake_dir/bin/cmake" ]] &&
		[[ -x "$cmake_dir/bin/ninja" ]] &&
		[[ -f "$cmake_dir/source.properties" ]] &&
		grep -Fqx "Pkg.Revision = $cmake_version" "$cmake_dir/source.properties"
}

if ! cmake_is_ready; then
	mkdir -p "$download_dir" "$sdk_root/cmake"
	if [[ ! -f "$archive" ]] ||
		! printf '%s  %s\n' "$cmake_sha256" "$archive" | sha256sum --check --status; then
		partial="$archive.partial"
		rm -f "$partial"
		curl --fail --location \
			--retry 5 --retry-all-errors --connect-timeout 15 \
			--output "$partial" "$cmake_url"
		printf '%s  %s\n' "$cmake_sha256" "$partial" | sha256sum --check --status
		mv "$partial" "$archive"
	fi

	temporary="$sdk_root/cmake/.${cmake_version}.tmp.$$"
	rm -rf "$temporary"
	mkdir -p "$temporary"
	unzip -q "$archive" -d "$temporary"
	rm -rf "$cmake_dir"
	mv "$temporary" "$cmake_dir"
fi

if ! cmake_is_ready; then
	echo >&2 "Android CMake $cmake_version installation is incomplete."
	exit 1
fi

echo "Android toolchain ready: NDK $ndk_version, CMake $cmake_version"
