#!/usr/bin/env bash
# Build, install and run the Android Auto prober, then print what it saw.
#
#   bash tools/auto-prober/probe.sh            # depth 2, the ordinary root
#   bash tools/auto-prober/probe.sh 3 true     # depth 3, the RECENT root
#
# This installs a SECOND app on the phone — com.soulstream.autoprober, about
# 50 KB, no permissions, no network, no storage, no UI. `adb uninstall
# com.soulstream.autoprober` removes it completely. It never signs in,
# downloads, joins a room, writes the config or touches the library; the only
# thing it force-stops is SoulStream, which the phone walk already does.
#
# Gradle comes from the GENERATED project's wrapper on purpose: that pins
# Gradle 8.14.3, AGP 8.11.0, Kotlin 1.9.25 and JDK 17, all of which are
# already in Kyle's Gradle cache, so this downloads nothing new. There is no
# gradle-wrapper.jar in this directory and there should not be one.
set -euo pipefail
ROOT=/f/Coding/SoulStream
cd "$ROOT"
source src-tauri/android/env.sh

DEPTH="${1:-2}"
RECENT="${2:-false}"
APK=tools/auto-prober/prober/build/outputs/apk/debug/prober-debug.apk
GRADLEW="$ROOT/src-tauri/gen/android/gradlew.bat"

test -f "$GRADLEW" || { echo "no generated Android project — run a normal build first"; exit 1; }

echo "== this installs com.soulstream.autoprober on the phone (adb uninstall com.soulstream.autoprober removes it)"
echo "== gradle $(date +%T)"
(
    cd tools/auto-prober
    MSYS_NO_PATHCONV=1 "$GRADLEW" :prober:assembleDebug -q 2>&1 | grep -v "^$" | tail -20 || true
)
test -f "$APK" || { echo "no prober APK — gradle's tail is above"; exit 1; }
ls -la "$APK"

echo "== install $(date +%T)"
"$ADB" install -r "$APK" > /dev/null

echo "== cold: force-stopping SoulStream $(date +%T)"
"$ADB" logcat -c
"$ADB" shell am force-stop com.soulstream.app
"$ADB" shell am start -W -n com.soulstream.autoprober/.ProbeActivity \
    --ei depth "$DEPTH" --ez recent "$RECENT" > /dev/null
sleep 7

echo
echo "== the probe (one JSON object per event)"
"$ADB" logcat -d -s SoulAutoProbe:I

echo
echo "== the root, as the service saw it"
"$ADB" logcat -d -s SoulStream:I | grep "auto root" | tail -3 || echo "  (no root line — the callback was never reached)"

# androidx/media #3158: a host that binds with nothing playing can put the
# service in a create/destroy loop at ~30 Hz. The singleton in MediaHub means
# nothing is allocated per cycle, but the loop itself is Android Auto's bug
# to fix — so this number is the thing to watch, and it is why those two
# lifecycle log lines exist at all. One or two is normal.
echo
echo "== androidx/media #3158: how many times the service was built"
"$ADB" logcat -d -s SoulStream:I | grep "auto service created" | tail -1 \
    || echo "  (no creation line — the service was never built)"
