#!/usr/bin/env bash
# Quick APK decompile for BLE protocol reverse engineering.
# Usage: ./decompile-app.sh com.example.app [out_dir]
#
# Pulls the APK from an ADB-connected device, decompiles with jadx,
# and prints the BLE command bytes used by the app.
set -e

PKG="${1:?usage: $0 <package> [out_dir]}"
OUT="${2:-/tmp/${PKG}-decompiled}"
APK="/tmp/${PKG}.apk"

ADB_OPTS=""
if [ -n "$ADB_TARGET" ]; then
  ADB_OPTS="-s $ADB_TARGET"
fi

# 1. Find APK on device
echo "==> Locating $PKG on device..."
APK_PATH=$(adb $ADB_OPTS shell pm path "$PKG" | sed 's/package://' | tr -d '\r' | head -1)
if [ -z "$APK_PATH" ]; then
  echo "ERROR: $PKG not installed on device"
  exit 1
fi
echo "    Found: $APK_PATH"

# 2. Pull APK
echo "==> Pulling APK..."
adb $ADB_OPTS pull "$APK_PATH" "$APK"
echo "    Saved to: $APK"

# 3. Install jadx if missing
if [ ! -x "$HOME/opt/jadx/bin/jadx" ]; then
  echo "==> Installing jadx..."
  mkdir -p ~/opt/jadx
  cd ~/opt/jadx
  wget -q https://github.com/skylot/jadx/releases/download/v1.5.0/jadx-1.5.0.zip -O jadx.zip
  unzip -q -o jadx.zip
  chmod +x bin/jadx
  cd - > /dev/null
fi

# 4. Decompile
echo "==> Decompiling to $OUT..."
~/opt/jadx/bin/jadx -d "$OUT" --no-res "$APK" 2>&1 | tail -5

# 5. Find BLE command classes
echo
echo "==> Searching for BLE command patterns..."
NET_CLASS=$(find "$OUT/sources" -name "NetConnectBle.java" -o -name "*Command*.java" -o -name "*Ble*.java" 2>/dev/null | head -5)
echo "    Found: $NET_CLASS"
echo

# 6. Extract every sendData call with its enclosing function name
if [ -n "$NET_CLASS" ]; then
  for f in $NET_CLASS; do
    echo "    --- $f ---"
    python3 -c "
import re
content = open('$f').read()
methods = re.split(r'(\n\s*public\s+(?:void|boolean|int|String|long)\s+\w+\s*\([^)]*\)\s*(?:throws\s+[\w,\s]+)?\s*\{)', content)
i = 1
while i < len(methods) - 1:
    sig = methods[i].strip().rstrip('{').strip()
    body = methods[i+1] if i+1 < len(methods) else ''
    m = re.search(r'sendData\(new int\[\]\{([^}]+)\}\)', body)
    if m:
        args = m.group(1).strip()
        bytes_str = ' '.join(f'{int(t):02X}' for t in re.findall(r'\d+', args))
        print(f'  {sig}')
        print(f'    raw:   {args}')
        print(f'    bytes: {bytes_str}')
        print()
    i += 2
"
  done
else
  echo "    No NetConnectBle/Ble/Command classes found. Manual grep:"
  echo "    grep -rn 'sendData\|writeCharacteristic' $OUT/sources | head -30"
fi
