#!/usr/bin/env bash
# Create android/local.properties with sdk.dir so Gradle finds the Android SDK.
# Run from repo root:  ./scripts/write-android-local-properties.sh
#   or:  ANDROID_HOME=/path/to/Sdk ./scripts/write-android-local-properties.sh
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
ANDROID_DIR="${REPO_ROOT}/android"
LOCAL_PROPS="${ANDROID_DIR}/local.properties"

SDK_DIR="${ANDROID_HOME:-${HOME}/Android/Sdk}"

if [[ ! -d "$SDK_DIR" ]]; then
  echo "Error: Android SDK not found at: $SDK_DIR" >&2
  echo "Set ANDROID_HOME to your SDK path (e.g. export ANDROID_HOME=\"\$HOME/Android/Sdk\")." >&2
  exit 1
fi

if command -v realpath &>/dev/null; then
  SDK_DIR=$(realpath "$SDK_DIR")
else
  SDK_DIR=$(readlink -f "$SDK_DIR" 2>/dev/null || echo "$SDK_DIR")
fi

if [[ ! -d "$ANDROID_DIR" ]]; then
  echo "Error: expected android/ at: $ANDROID_DIR" >&2
  exit 1
fi

printf '## This file is machine-specific (not committed). Points Gradle to the Android SDK.\nsdk.dir=%s\n' "$SDK_DIR" > "$LOCAL_PROPS"
echo "Wrote $LOCAL_PROPS"
echo "sdk.dir=$SDK_DIR"
