#!/usr/bin/env bash
# Reapply the Metro port forward on every attached device.
# Wireless ADB drops the reverse tunnel whenever it reconnects, which makes the
# dev client fail with "Unable to load script".
set -euo pipefail

PORT="${1:-${RCT_METRO_PORT:-8081}}"

ADB="$(command -v adb || true)"
if [ -z "$ADB" ]; then
  for sdk in "${ANDROID_HOME:-}" "${ANDROID_SDK_ROOT:-}" "$HOME/Android/Sdk"; do
    if [ -n "$sdk" ] && [ -x "$sdk/platform-tools/adb" ]; then
      ADB="$sdk/platform-tools/adb"
      break
    fi
  done
fi

if [ -z "$ADB" ]; then
  echo "adb not found. Set ANDROID_HOME or add platform-tools to PATH." >&2
  exit 1
fi

devices="$("$ADB" devices | awk 'NR>1 && $2=="device" {print $1}')"
if [ -z "$devices" ]; then
  echo "No device attached. Connect one (adb devices) and retry." >&2
  exit 1
fi

for serial in $devices; do
  "$ADB" -s "$serial" reverse "tcp:$PORT" "tcp:$PORT" >/dev/null
  echo "reverse tcp:$PORT -> $serial"
done
