#!/data/data/com.termux/files/usr/bin/bash
#
# grest-adb.sh — connect THIS phone to the Grest server over ADB.
# Phone runs its adb server on 5037 (local), tunneled to the server's 5039
# (5037 is already used on the server). Server then: adb -P 5039 devices.
#
# Download then run (do NOT pipe to bash):
#   curl -fsSL https://files.winds-os.com/grest-adb.sh -o grest-adb.sh && bash grest-adb.sh
#
# Android 11+. Keep Termux OPEN.

SERVER_USER="usr1"; SERVER_HOST="82.25.86.78"
PHONE_ADB_PORT="5037"     # phone's local adb server
SERVER_TUNNEL_PORT="5039" # maps to server side (5037 is busy there)

echo "=============================================================="
echo "   Grest: connect THIS phone (Galaxy S24) to the server"
echo "=============================================================="
[ -d /data/data/com.termux ] || { echo "Run inside Termux."; exit 1; }
[ -t 0 ] || { echo "Don't pipe to bash. Use: curl ... -o grest-adb.sh && bash grest-adb.sh"; exit 1; }

echo "[1/6] Installing adb + ssh..."
pkg install -y android-tools openssh >/dev/null 2>&1 || pkg install -y android-tools openssh

# Make sure a clean local adb server is running on 5037
adb kill-server >/dev/null 2>&1
adb start-server >/dev/null 2>&1

cat <<'GUIDE'
[2/6] PHONE: Settings > Developer options > Wireless debugging = ON, tap to open.
      PAIR popup ('Pair device with pairing code'): a 6-digit code + a port.
      MAIN screen ('IP address & Port'): the CONNECT port (different number).
GUIDE

while :; do
  read -r -p "[3/6] PAIR port: " PP; read -r -p "      PAIR code (6 digits): " PC
  if [ -n "$PP" ] && [ -n "$PC" ]; then adb pair 127.0.0.1:"$PP" "$PC" && break; echo "  pair failed — reopen popup (port changes) & retry"; else echo "  both required"; fi
done
while :; do read -r -p "[4/6] CONNECT port: " CP; [ -n "$CP" ] && break; done
adb connect 127.0.0.1:"$CP"; sleep 1

echo "[5/6] This phone now sees:"
adb devices -l
# must show a real device (your phone), not empty
if [ "$(adb devices | awk 'NR>1 && $2=="device"' | wc -l)" -eq 0 ]; then
  echo "  !! No authorized device. The CONNECT port was likely wrong, or pairing"
  echo "     didn't stick. Reopen Wireless debugging and re-run."
  exit 1
fi

echo "[6/6] Tunneling phone adb server (5037) -> server port ${SERVER_TUNNEL_PORT}."
echo "      (enter SERVER password if asked; LEAVE THIS RUNNING)"
echo "--------------------------------------------------------------"
exec ssh -N -o ServerAliveInterval=30 -o ExitOnForwardFailure=yes \
  -R 127.0.0.1:${SERVER_TUNNEL_PORT}:127.0.0.1:${PHONE_ADB_PORT} \
  "${SERVER_USER}@${SERVER_HOST}"
