#!/bin/sh
# Provision the pinned Android build toolchain into TOOLCHAIN_DIR (default
# $HOME/toolchains): JDK 17, Android cmdline-tools, SDK platform, build-tools,
# NDK, and Gradle. Idempotent: re-running only fills what is missing. Writes an
# env.sh to source before building. This is what CI runs to get a build host.
set -eu

root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
. "$root/versions"

dir=${TOOLCHAIN_DIR:-$HOME/toolchains}
sdk="$dir/android-sdk"
mkdir -p "$dir/dl"

# JDK (Temurin, exact pinned release; + must be %2B in the URL).
if [ ! -x "$dir/jdk17/bin/java" ]; then
	echo "setup: JDK $JDK_RELEASE"
	rel=$(printf '%s' "$JDK_RELEASE" | sed 's/+/%2B/')
	curl -fsSL "https://api.adoptium.net/v3/binary/version/jdk-${rel}/linux/x64/jdk/hotspot/normal/eclipse" -o "$dir/dl/jdk.tar.gz"
	mkdir -p "$dir/jdk17"
	tar xzf "$dir/dl/jdk.tar.gz" -C "$dir/jdk17" --strip-components=1
fi
export JAVA_HOME="$dir/jdk17"
export PATH="$JAVA_HOME/bin:$PATH"

# Android cmdline-tools.
if [ ! -x "$sdk/cmdline-tools/latest/bin/sdkmanager" ]; then
	echo "setup: cmdline-tools $ANDROID_CMDLINE_TOOLS"
	curl -fsSL "https://dl.google.com/android/repository/commandlinetools-linux-${ANDROID_CMDLINE_TOOLS}_latest.zip" -o "$dir/dl/clt.zip"
	rm -rf "$dir/dl/clt"
	python3 -m zipfile -e "$dir/dl/clt.zip" "$dir/dl/clt"
	mkdir -p "$sdk/cmdline-tools"
	rm -rf "$sdk/cmdline-tools/latest"
	mv "$dir/dl/clt/cmdline-tools" "$sdk/cmdline-tools/latest"
	chmod +x "$sdk/cmdline-tools/latest/bin/"*
fi

# SDK packages.
echo "setup: sdk packages"
yes | "$sdk/cmdline-tools/latest/bin/sdkmanager" --licenses >/dev/null 2>&1 || true
"$sdk/cmdline-tools/latest/bin/sdkmanager" \
	"platform-tools" \
	"platforms;android-${ANDROID_PLATFORM}" \
	"build-tools;${ANDROID_BUILD_TOOLS}" \
	"ndk;${ANDROID_NDK}" >/dev/null

# Gradle.
if [ ! -x "$dir/gradle-${GRADLE_VERSION}/bin/gradle" ]; then
	echo "setup: Gradle $GRADLE_VERSION"
	curl -fsSL "https://services.gradle.org/distributions/gradle-${GRADLE_VERSION}-bin.zip" -o "$dir/dl/gradle.zip"
	python3 -m zipfile -e "$dir/dl/gradle.zip" "$dir"
	chmod +x "$dir/gradle-${GRADLE_VERSION}/bin/gradle"
fi

# Go (pinned; builds rsh).
if [ ! -x "$dir/go/bin/go" ]; then
	echo "setup: Go $GO_VERSION"
	curl -fsSL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" -o "$dir/dl/go.tar.gz"
	rm -rf "$dir/go"
	tar xzf "$dir/dl/go.tar.gz" -C "$dir"
fi

# Emit the env to source before building.
cat > "$dir/env.sh" <<EOF
export JAVA_HOME="$dir/jdk17"
export GOROOT="$dir/go"
export ANDROID_HOME="$sdk"
export ANDROID_SDK_ROOT="$sdk"
export ANDROID_NDK_HOME="$sdk/ndk/${ANDROID_NDK}"
export GRADLE_HOME="$dir/gradle-${GRADLE_VERSION}"
export PATH="\$JAVA_HOME/bin:$dir/go/bin:\$GRADLE_HOME/bin:$sdk/cmdline-tools/latest/bin:$sdk/platform-tools:\$PATH"
EOF

echo "setup: done; source $dir/env.sh"
