#!/bin/bash
# Start voice bridge on Debian (where phone is connected via USB)
# Run this ONCE before starting relay.py on PlugAI
#
# Correct order:
# 1. Launch app
# 2. Open voice chat (one-shot frida attach + detach)
# 3. Wait for libantaudio.so
# 4. Attach frida with voice_bridge_v8.js (lib already loaded, stable)
# 5. Setup adb forward

set -e

SCRIPT_DIR="/home/ceshi/reverse-lab/antaf/scripts"
FRIDA="/home/ceshi/.local/bin/frida"

echo "[1] Launching Antaf app..."
adb shell "monkey -p com.antgroup.aijk.android -c android.intent.category.LAUNCHER 1" 2>/dev/null
sleep 3

PID=$(adb shell ps -A | grep 'com.antgroup.aijk.android$' | awk '{print $2}')
if [ -z "$PID" ]; then echo "ERROR: App not running"; exit 1; fi
echo "  PID=$PID"

echo "[2] Opening voice chat..."
timeout 8 $FRIDA -U -p $PID -l $SCRIPT_DIR/open_voice.js --no-pause -q 2>/dev/null || true
sleep 3

echo "[3] Waiting for libantaudio.so..."
sleep 2

echo "[4] Attaching voice_bridge_v8..."
pkill -f frida 2>/dev/null || true
sleep 1
adb forward tcp:18901 tcp:18901
nohup $FRIDA -U -p $PID -l $SCRIPT_DIR/voice_bridge_v8.js > /tmp/frida_voice.log 2>&1 &
sleep 5
tail -5 /tmp/frida_voice.log

echo ""
echo "=== Voice bridge ready on :18901 ==="
