#!/bin/bash
# ADB test helpers for NFC /dev/nfc_dev

DEV="/dev/nfc_dev"
TMP="/data/local/tmp"

usage() {
    echo "Usage: $0 <command>"
    echo ""
    echo "Commands:"
    echo "  push-native     Build (if needed) and push nfc_test binary to device"
    echo "  run-native      Run nfc_test on device (blocking, Ctrl+C to stop)"
    echo "  push-java       Push NfcTest.class to device and run with dalvikvm"
    echo "  quick-read      Quick read with adb shell (non-blocking, may miss events)"
    echo "  check-dev       Check if /dev/nfc_dev exists and its permissions"
    echo "  logcat          Tail kernel log related to NFC"
    echo "  all             push-native + check-dev + run-native"
    echo ""
    echo "Examples:"
    echo "  $0 push-native"
    echo "  $0 run-native"
    echo "  $0 quick-read"
}

push_native() {
    if [ ! -f "nfc_test" ]; then
        if [ -f "build.sh" ]; then
            ./build.sh || exit 1
        else
            echo "nfc_test binary not found and build.sh missing."
            exit 1
        fi
    fi
    echo "Pushing nfc_test -> $TMP/nfc_test"
    adb push nfc_test "$TMP/nfc_test"
    adb shell chmod 755 "$TMP/nfc_test"
}

run_native() {
    echo "Running nfc_test on device..."
    adb shell "$TMP/nfc_test"
}

push_java() {
    if [ ! -f "NfcTest.class" ]; then
        echo "Compiling NfcTest.java..."
        javac NfcTest.java || exit 1
    fi
    echo "Pushing NfcTest.class -> $TMP/"
    adb push NfcTest.class "$TMP/"
    echo "Running with dalvikvm..."
    # Android 8+ uses app_process directly; older devices use dalvikvm
    adb shell "cd $TMP && dalvikvm -cp $TMP NfcTest 2>/dev/null || app_process -Djava.class.path=$TMP / NfcTest"
}

quick_read() {
    echo "Quick reading from $DEV (hex dump)..."
    adb shell "while true; do dd if=$DEV bs=1 count=32 2>/dev/null | hexdump -C; done"
}

check_dev() {
    echo "Checking device node..."
    adb shell "ls -l $DEV; echo '---'; getenforce; echo '---'; id"
}

logcat_nfc() {
    echo "Tailing kernel log for NFC..."
    adb shell "dmesg -w | grep -i nfc" 2>/dev/null || adb shell "logcat -d | grep -i nfc"
}

case "${1:-}" in
    push-native) push_native ;;
    run-native)  run_native ;;
    push-java)   push_java ;;
    quick-read)  quick_read ;;
    check-dev)   check_dev ;;
    logcat)      logcat_nfc ;;
    all)         push_native && check_dev && run_native ;;
    *)           usage ;;
esac
