1 #!/usr/bin/env bash
2 # ──────────────────────────────────────────────────────────────────────────────
3 # build-kotlin.sh — Cross-compile libonde for Android and generate Kotlin bindings
4 # ──────────────────────────────────────────────────────────────────────────────
5 #
6 # This script:
7 # 1. Builds the `uniffi-bindgen` CLI tool (host binary).
8 # 2. Cross-compiles the `onde` cdylib (libonde.so) for each Android target.
9 # 3. Runs `uniffi-bindgen generate` to produce the Kotlin source from the
10 # compiled library.
11 # 4. Copies the .so files into the Android library's jniLibs directories.
12 #
13 # Prerequisites:
14 # - Rust toolchain with Android targets installed:
15 # rustup target add aarch64-linux-android armv7-linux-androideabi \
16 # x86_64-linux-android i686-linux-android
17 # - Android NDK installed (set ANDROID_NDK_HOME or auto-detected from ANDROID_HOME)
18 # - cargo, rustc on PATH
19 #
20 # Usage:
21 # ./build-kotlin.sh # Build all targets (release)
22 # ./build-kotlin.sh --debug # Build all targets (debug)
23 # ./build-kotlin.sh --target aarch64-linux-android # Single target
24 # ./build-kotlin.sh --help # Show usage
25 #
26 # Environment variables:
27 # ANDROID_NDK_HOME — Path to the Android NDK (e.g. ~/Library/Android/sdk/ndk/27.2.12479018)
28 # ANDROID_HOME — Path to the Android SDK (NDK auto-detected under ndk/)
29 # ONDE_FEATURES — Extra Cargo features to enable (comma-separated, default: none)
30 # CARGO — Path to cargo binary (default: cargo)
31 # ──────────────────────────────────────────────────────────────────────────────
32 set -euo pipefail
33
34 # ── Constants ─────────────────────────────────────────────────────────────────
35
36 SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
37 CRATE_DIR="$SCRIPT_DIR"
38 KOTLIN_PROJECT_DIR="$CRATE_DIR/kotlin"
39 KOTLIN_LIB_DIR="$KOTLIN_PROJECT_DIR/onde"
40 JNILIBS_DIR="$KOTLIN_LIB_DIR/src/main/jniLibs"
41 # UniFFI's --out-dir receives the Kotlin source root; it creates the
42 # package directory structure (com/ondeinference/onde/) automatically
43 # based on the package_name in uniffi.toml.
44 KOTLIN_SRC_ROOT="$KOTLIN_LIB_DIR/src/main/kotlin"
45 GENERATED_KT_DIR="$KOTLIN_SRC_ROOT/com/ondeinference/onde"
46 BINDGEN_CRATE_DIR="$CRATE_DIR/uniffi-bindgen"
47
48 CARGO="${CARGO:-cargo}"
49 PROFILE="release"
50 PROFILE_DIR="release"
51
52 # Map Rust target triples to Android ABI folder names and NDK toolchain prefixes.
53 declare -A TARGET_TO_ABI=(
54 ["aarch64-linux-android"]="arm64-v8a"
55 ["armv7-linux-androideabi"]="armeabi-v7a"
56 ["x86_64-linux-android"]="x86_64"
57 ["i686-linux-android"]="x86"
58 )
59
60 declare -A TARGET_TO_CC_PREFIX=(
61 ["aarch64-linux-android"]="aarch64-linux-android"
62 ["armv7-linux-androideabi"]="armv7a-linux-androideabi"
63 ["x86_64-linux-android"]="x86_64-linux-android"
64 ["i686-linux-android"]="i686-linux-android"
65 )
66
67 ALL_TARGETS=("aarch64-linux-android" "armv7-linux-androideabi" "x86_64-linux-android" "i686-linux-android")
68 SELECTED_TARGETS=()
69
70 # Minimum Android API level — must match the library's minSdk (24).
71 MIN_API=24
72
73 # ── Helpers ───────────────────────────────────────────────────────────────────
74
75 RED='\033[0;31m'
76 GREEN='\033[0;32m'
77 YELLOW='\033[0;33m'
78 CYAN='\033[0;36m'
79 BOLD='\033[1m'
80 NC='\033[0m' # No Color
81
82 log() { echo -e "${CYAN}[onde]${NC} $*"; }
83 ok() { echo -e "${GREEN}[onde]${NC} $*"; }
84 warn() { echo -e "${YELLOW}[onde]${NC} $*"; }
85 err() { echo -e "${RED}[onde]${NC} $*" >&2; }
86 die() { err "$@"; exit 1; }
87
88 usage() {
89 cat <<EOF
90 Usage: $(basename "$0") [OPTIONS]
91
92 Cross-compile libonde for Android and generate Kotlin (UniFFI) bindings.
93
94 Options:
95 --debug Build in debug mode (default: release)
96 --target <triple> Build only for the specified Rust target triple.
97 Can be repeated. If omitted, all four Android targets
98 are built: ${ALL_TARGETS[*]}
99 --generate-only Skip Rust compilation; only run uniffi-bindgen to
100 regenerate the Kotlin source from an existing .so.
101 --ndk <path> Explicit path to the Android NDK.
102 --help, -h Show this help message.
103
104 Environment:
105 ANDROID_NDK_HOME Android NDK path (auto-detected from ANDROID_HOME)
106 ANDROID_HOME Android SDK path (NDK searched under ndk/)
107 ONDE_FEATURES Extra Cargo features, comma-separated
108 CARGO Path to cargo (default: cargo)
109
110 Examples:
111 # Full build for all Android ABIs (release)
112 ./build-kotlin.sh
113
114 # Debug build, arm64 only
115 ./build-kotlin.sh --debug --target aarch64-linux-android
116
117 # Re-generate Kotlin source without recompiling Rust
118 ./build-kotlin.sh --generate-only
119 EOF
120 exit 0
121 }
122
123 # ── Argument parsing ──────────────────────────────────────────────────────────
124
125 GENERATE_ONLY=false
126
127 while [[ $# -gt 0 ]]; do
128 case "$1" in
129 --debug)
130 PROFILE="debug"
131 PROFILE_DIR="debug"
132 shift
133 ;;
134 --target)
135 [[ -n "${2:-}" ]] || die "--target requires a Rust target triple"
136 SELECTED_TARGETS+=("$2")
137 shift 2
138 ;;
139 --generate-only)
140 GENERATE_ONLY=true
141 shift
142 ;;
143 --ndk)
144 [[ -n "${2:-}" ]] || die "--ndk requires a path"
145 ANDROID_NDK_HOME="$2"
146 shift 2
147 ;;
148 --help|-h)
149 usage
150 ;;
151 *)
152 die "Unknown option: $1 (try --help)"
153 ;;
154 esac
155 done
156
157 # Default to all targets if none specified.
158 if [[ ${#SELECTED_TARGETS[@]} -eq 0 ]]; then
159 SELECTED_TARGETS=("${ALL_TARGETS[@]}")
160 fi
161
162 # Validate selected targets.
163 for t in "${SELECTED_TARGETS[@]}"; do
164 if [[ -z "${TARGET_TO_ABI[$t]:-}" ]]; then
165 die "Unknown Android target: $t\nValid targets: ${ALL_TARGETS[*]}"
166 fi
167 done
168
169 # ── Locate the Android NDK ────────────────────────────────────────────────────
170
171 find_ndk() {
172 # 1. Explicit ANDROID_NDK_HOME
173 if [[ -n "${ANDROID_NDK_HOME:-}" && -d "$ANDROID_NDK_HOME" ]]; then
174 echo "$ANDROID_NDK_HOME"
175 return
176 fi
177
178 # 2. Search inside ANDROID_HOME/ndk/ — pick the newest version.
179 if [[ -n "${ANDROID_HOME:-}" && -d "$ANDROID_HOME/ndk" ]]; then
180 local latest
181 latest=$(find "$ANDROID_HOME/ndk" -mindepth 1 -maxdepth 1 -type d | sort -V | tail -1)
182 if [[ -n "$latest" ]]; then
183 echo "$latest"
184 return
185 fi
186 fi
187
188 # 3. Common macOS SDK location.
189 local default_sdk="$HOME/Library/Android/sdk"
190 if [[ -d "$default_sdk/ndk" ]]; then
191 local latest
192 latest=$(find "$default_sdk/ndk" -mindepth 1 -maxdepth 1 -type d | sort -V | tail -1)
193 if [[ -n "$latest" ]]; then
194 echo "$latest"
195 return
196 fi
197 fi
198
199 # 4. Linux default.
200 local linux_sdk="$HOME/Android/Sdk"
201 if [[ -d "$linux_sdk/ndk" ]]; then
202 local latest
203 latest=$(find "$linux_sdk/ndk" -mindepth 1 -maxdepth 1 -type d | sort -V | tail -1)
204 if [[ -n "$latest" ]]; then
205 echo "$latest"
206 return
207 fi
208 fi
209
210 return 1
211 }
212
213 if ! $GENERATE_ONLY; then
214 NDK_HOME=$(find_ndk) || die \
215 "Android NDK not found.\n" \
216 "Set ANDROID_NDK_HOME or ANDROID_HOME, or pass --ndk <path>."
217
218 log "Using Android NDK: ${BOLD}$NDK_HOME${NC}"
219
220 # Determine the host OS tag for the NDK toolchain.
221 case "$(uname -s)" in
222 Darwin*) HOST_TAG="darwin-x86_64" ;;
223 Linux*) HOST_TAG="linux-x86_64" ;;
224 MINGW*|MSYS*|CYGWIN*) HOST_TAG="windows-x86_64" ;;
225 *) die "Unsupported host OS: $(uname -s)" ;;
226 esac
227
228 TOOLCHAIN_BIN="$NDK_HOME/toolchains/llvm/prebuilt/$HOST_TAG/bin"
229 [[ -d "$TOOLCHAIN_BIN" ]] || die "NDK toolchain not found at: $TOOLCHAIN_BIN"
230 fi
231
232 # ── Step 1: Build the uniffi-bindgen CLI (host) ──────────────────────────────
233
234 log "Building ${BOLD}uniffi-bindgen${NC} CLI (host)..."
235
236 $CARGO build \
237 --manifest-path "$BINDGEN_CRATE_DIR/Cargo.toml" \
238 --release \
239 --quiet
240
241 UNIFFI_BINDGEN="$BINDGEN_CRATE_DIR/target/release/uniffi-bindgen"
242 # If the binary lands in the workspace target/ dir instead, try that too.
243 if [[ ! -x "$UNIFFI_BINDGEN" ]]; then
244 # When the crate shares a workspace target dir (or no workspace), the
245 # binary may be under the onde crate's target/ or the workspace root.
246 for candidate in \
247 "$CRATE_DIR/target/release/uniffi-bindgen" \
248 "$CRATE_DIR/../../../target/release/uniffi-bindgen"; do
249 if [[ -x "$candidate" ]]; then
250 UNIFFI_BINDGEN="$candidate"
251 break
252 fi
253 done
254 fi
255
256 [[ -x "$UNIFFI_BINDGEN" ]] || die "uniffi-bindgen binary not found after build."
257 ok "uniffi-bindgen ready: $UNIFFI_BINDGEN"
258
259 # ── Step 2: Cross-compile the Rust cdylib for each Android target ─────────────
260
261 # We'll remember the path to the first successfully built .so so we can use
262 # it for bindgen (any ABI's .so contains the same UniFFI metadata).
263 FIRST_SO=""
264
265 if ! $GENERATE_ONLY; then
266 FEATURES_FLAG=""
267 if [[ -n "${ONDE_FEATURES:-}" ]]; then
268 FEATURES_FLAG="--features $ONDE_FEATURES"
269 fi
270
271 for TARGET in "${SELECTED_TARGETS[@]}"; do
272 ABI="${TARGET_TO_ABI[$TARGET]}"
273 CC_PREFIX="${TARGET_TO_CC_PREFIX[$TARGET]}"
274
275 log "Compiling ${BOLD}libonde.so${NC} for ${BOLD}$TARGET${NC} ($ABI)..."
276
277 # Set up the CC/CXX/AR/RANLIB environment for the NDK clang toolchain
278 # so that cc-rs, cmake, and any -sys crates find the right compiler.
279 export CC="${TOOLCHAIN_BIN}/${CC_PREFIX}${MIN_API}-clang"
280 export CXX="${TOOLCHAIN_BIN}/${CC_PREFIX}${MIN_API}-clang++"
281 export AR="${TOOLCHAIN_BIN}/llvm-ar"
282 export RANLIB="${TOOLCHAIN_BIN}/llvm-ranlib"
283
284 # Cargo uses the uppercase-dashed form of the target for env overrides.
285 TARGET_UPPER=$(echo "$TARGET" | tr '[:lower:]-' '[:upper:]_')
286 export "CARGO_TARGET_${TARGET_UPPER}_LINKER=$CC"
287
288 if [[ "$PROFILE" == "release" ]]; then
289 PROFILE_FLAG="--release"
290 else
291 PROFILE_FLAG=""
292 fi
293
294 $CARGO build \
295 --manifest-path "$CRATE_DIR/Cargo.toml" \
296 --lib \
297 --target "$TARGET" \
298 $PROFILE_FLAG \
299 $FEATURES_FLAG
300
301 # Locate the built .so
302 SO_PATH="$CRATE_DIR/target/$TARGET/$PROFILE_DIR/libonde.so"
303 if [[ ! -f "$SO_PATH" ]]; then
304 # Some workspace layouts put target/ at the workspace root.
305 for candidate in \
306 "$CRATE_DIR/../../../target/$TARGET/$PROFILE_DIR/libonde.so" \
307 "$CRATE_DIR/../../target/$TARGET/$PROFILE_DIR/libonde.so"; do
308 if [[ -f "$candidate" ]]; then
309 SO_PATH="$(cd "$(dirname "$candidate")" && pwd)/$(basename "$candidate")"
310 break
311 fi
312 done
313 fi
314
315 [[ -f "$SO_PATH" ]] || die "libonde.so not found for $TARGET at expected paths."
316
317 # Copy into jniLibs/
318 mkdir -p "$JNILIBS_DIR/$ABI"
319 cp "$SO_PATH" "$JNILIBS_DIR/$ABI/libonde.so"
320 ok " → $JNILIBS_DIR/$ABI/libonde.so ($(du -h "$JNILIBS_DIR/$ABI/libonde.so" | cut -f1))"
321
322 if [[ -z "$FIRST_SO" ]]; then
323 FIRST_SO="$SO_PATH"
324 fi
325 done
326 else
327 # Generate-only: find an existing .so to extract metadata from.
328 for TARGET in "${SELECTED_TARGETS[@]}"; do
329 for candidate in \
330 "$CRATE_DIR/target/$TARGET/$PROFILE_DIR/libonde.so" \
331 "$CRATE_DIR/../../../target/$TARGET/$PROFILE_DIR/libonde.so" \
332 "$JNILIBS_DIR/${TARGET_TO_ABI[$TARGET]}/libonde.so"; do
333 if [[ -f "$candidate" ]]; then
334 FIRST_SO="$candidate"
335 break 2
336 fi
337 done
338 done
339
340 # Also try the host dylib (macOS .dylib, Linux .so) — uniffi-bindgen
341 # only needs the metadata, not a runnable Android binary.
342 if [[ -z "$FIRST_SO" ]]; then
343 for ext in dylib so; do
344 candidate="$CRATE_DIR/target/$PROFILE_DIR/libonde.$ext"
345 if [[ -f "$candidate" ]]; then
346 FIRST_SO="$candidate"
347 break
348 fi
349 done
350 fi
351
352 [[ -n "$FIRST_SO" ]] || die "No compiled libonde found. Run without --generate-only first."
353 log "Using existing library for bindgen: $FIRST_SO"
354 fi
355
356 # ── Step 3: Generate Kotlin bindings via uniffi-bindgen ───────────────────────
357
358 log "Generating Kotlin bindings..."
359
360 mkdir -p "$KOTLIN_SRC_ROOT"
361
362 $UNIFFI_BINDGEN generate \
363 --library "$FIRST_SO" \
364 --language kotlin \
365 --out-dir "$KOTLIN_SRC_ROOT" \
366 --config "$CRATE_DIR/uniffi.toml"
367
368 # Count generated files.
369 KT_COUNT=$(find "$GENERATED_KT_DIR" -name '*.kt' 2>/dev/null | wc -l | tr -d ' ')
370 ok "Generated ${BOLD}$KT_COUNT${NC} Kotlin file(s) in $GENERATED_KT_DIR"
371
372 # List them for visibility.
373 find "$GENERATED_KT_DIR" -name '*.kt' -exec basename {} \; | sort | while read -r f; do
374 log " • $f"
375 done
376
377 # ── Step 4: Summary ──────────────────────────────────────────────────────────
378
379 echo ""
380 ok "════════════════════════════════════════════════════════════════════"
381 ok " Onde Kotlin library build complete!"
382 ok "════════════════════════════════════════════════════════════════════"
383 echo ""
384
385 log "Native libraries:"
386 for TARGET in "${SELECTED_TARGETS[@]}"; do
387 ABI="${TARGET_TO_ABI[$TARGET]}"
388 SO="$JNILIBS_DIR/$ABI/libonde.so"
389 if [[ -f "$SO" ]]; then
390 SIZE=$(du -h "$SO" | cut -f1)
391 ok " $ABI → $SIZE"
392 else
393 warn " $ABI → (not built)"
394 fi
395 done
396
397 echo ""
398 log "Kotlin source: $GENERATED_KT_DIR"
399 log "Android lib: $KOTLIN_LIB_DIR"
400 echo ""
401 log "Next steps:"
402 log " 1. Open ${BOLD}$KOTLIN_PROJECT_DIR${NC} in Android Studio, or"
403 log " 2. Add the library as a dependency in your app's build.gradle.kts:"
404 log " ${BOLD}implementation(project(\":onde\"))${NC}"
405 log " 3. Or publish the AAR: ${BOLD}cd $KOTLIN_PROJECT_DIR && ./gradlew :onde:assembleRelease${NC}"
406 echo ""