#!/bin/bash
# NDK cross-compile script for nfc_test.c
# Target: aarch64-linux-android (arm64)

set -e

NDK_VERSION="27.0.12077973"
NDK_HOME="${ANDROID_NDK:-$HOME/Library/Android/sdk/ndk/$NDK_VERSION}"

if [ ! -d "$NDK_HOME" ]; then
    echo "NDK not found at $NDK_HOME"
    echo "Trying other versions..."
    for v in "$HOME"/Library/Android/sdk/ndk/*; do
        if [ -d "$v" ]; then
            NDK_HOME="$v"
            echo "Found NDK: $NDK_HOME"
            break
        fi
    done
fi

if [ ! -d "$NDK_HOME" ]; then
    echo "Error: Android NDK not found. Set ANDROID_NDK or install NDK."
    exit 1
fi

HOST_TAG="darwin-x86_64"
TOOLCHAIN="$NDK_HOME/toolchains/llvm/prebuilt/$HOST_TAG"
CC="$TOOLCHAIN/bin/aarch64-linux-android21-clang"
STRIP="$TOOLCHAIN/bin/llvm-strip"

if [ ! -f "$CC" ]; then
    echo "Error: Compiler not found: $CC"
    exit 1
fi

TARGET="nfc_test"

echo "Building $TARGET with NDK ($NDK_HOME)..."
"$CC" -O2 -Wall nfc_test.c -o "$TARGET"
"$STRIP" "$TARGET"

echo "Build success: ./$TARGET"
echo ""
echo "Push and run on device:"
echo "  adb push $TARGET /data/local/tmp/"
echo "  adb shell chmod 755 /data/local/tmp/$TARGET"
echo "  adb shell /data/local/tmp/$TARGET"
