#!/system/bin/sh
# One-command NEW device setup. Writes the config, pulls the minicap/minitouch
# prebuilts for THIS device's abi+sdk plus the agent + scripts + boot APK from
# the VPS, installs boot persistence, and starts — all over plain HTTP.
#
# Run as ROOT on the new device, pasting the lines printed by add-device.sh.
# On ROMs with no working DNS, fetch by IP with TB_BASE — the agent is then told
# to dial that IP for wss too (TB_SERVER_IP), while still presenting the domain
# for Host routing + TLS, so nothing depends on the device resolving the name:
#   busybox wget -O setup.sh http://<IP>:8088/device-setup.sh
#   TB_BASE=http://<IP>:8088 TB_ID=x TB_TOKEN=y sh setup.sh
BASE="${TB_BASE:-http://tbremote.nozim-dev.uz:8088}"
DIR=/data/local/tmp
: "${TB_TOKEN:?TB_TOKEN required — pass it before sh}"
: "${TB_SERVER:=wss://tbremote.nozim-dev.uz/agent}"
# TB_ID is OPTIONAL: left blank, the device self-names by its serial number
# (an enroll token is claimed under that serial on first connect).
: "${TB_ID:=}"
TB_TOKEN="$(echo "$TB_TOKEN" | busybox tr -d ' \r\n')"
TB_ID="$(echo "$TB_ID" | busybox tr -d ' \r\n')"
if [ -z "$TB_ID" ]; then
  TB_ID="$(getprop ro.boot.serialno 2>/dev/null | busybox tr -d ' \r\n')"
  [ -n "$TB_ID" ] || TB_ID="$(getprop ro.serialno 2>/dev/null | busybox tr -d ' \r\n')"
fi
# sanitize to the server's allowed id charset (a stray serial char would be rejected)
TB_ID="$(echo "$TB_ID" | busybox tr -cd 'A-Za-z0-9._-')"
: "${TB_ID:?could not read a serial number — pass TB_ID explicitly}"
mkdir -p "$DIR"; cd "$DIR" || exit 1
say() { echo "[setup] $*"; }

# If BASE is an IP (DNS-less mode), pin that IP for the agent's wss dial too.
BASE_HOST="${BASE#*://}"; BASE_HOST="${BASE_HOST%%[:/]*}"
case "$BASE_HOST" in
  [0-9]*[0-9]) SERVER_IP="$BASE_HOST" ;;  # numeric host -> no DNS on this device
  *) SERVER_IP="" ;;
esac

# 1) config — the supervisor and boot hooks read this (stays in /data across OTA)
{
  echo "TB_SERVER=$TB_SERVER"
  echo "TB_ID=$TB_ID"
  echo "TB_TOKEN=$TB_TOKEN"
  [ -n "$SERVER_IP" ] && echo "export TB_SERVER_IP=$SERVER_IP"
} > "$DIR/tb-agent.env"
say "config written (id=$TB_ID${SERVER_IP:+, wss via IP $SERVER_IP})"

# 2) minicap/minitouch for THIS device's abi + sdk (the whole dist tree is served)
ABI="$(getprop ro.product.cpu.abi 2>/dev/null | busybox tr -d ' \r\n')"
SDK="$(getprop ro.build.version.sdk 2>/dev/null | busybox tr -d ' \r\n')"
say "abi=$ABI sdk=$SDK"
pull() { busybox wget -O "$2.new" "$1" 2>/dev/null && [ -s "$2.new" ] && busybox mv "$2.new" "$2"; r=$?; rm -f "$2.new" 2>/dev/null; return $r; }
pull "$BASE/minicap/$ABI/bin/minicap" minicap && chmod 755 minicap && say "minicap ✓" || say "minicap FAILED (abi served on VPS?)"
pull "$BASE/minitouch/$ABI/bin/minitouch" minitouch && chmod 755 minitouch && say "minitouch ✓" || say "minitouch skipped (optional)"
# minicap.so is per (abi, sdk). Try this device's own sdk, then walk DOWN to the
# newest one the server actually carries. The old fallback jumped straight to
# android-22, so any box newer than what we ship (TB40 = 30, TB50 later) landed
# on a decade-old build instead of the closest match.
got_so=""
for try_sdk in 34 33 32 31 30 29 28 27 26 25 24 23 22 21; do
  [ "$try_sdk" -le "${SDK:-0}" ] 2>/dev/null || continue   # never newer than the device
  if pull "$BASE/minicap/$ABI/lib/android-$try_sdk/minicap.so" minicap.so; then
    got_so="$try_sdk"; break
  fi
done
[ -n "$got_so" ] && say "minicap.so ✓ (android-$got_so)" \
  || say "minicap.so FAILED — check VPS dist for abi=$ABI sdk=$SDK"

# 3) agent + scripts + boot APK + persistence + start — reuse the updater (DRY),
# passing TB_BASE so it fetches over the same (possibly IP) channel
say "installing agent + boot persistence…"
if busybox wget -O tb-device-update.sh "$BASE/device-update.sh" 2>/dev/null && [ -s tb-device-update.sh ]; then
  TB_BASE="$BASE" sh tb-device-update.sh
else
  say "could not fetch device-update.sh from $BASE"
fi
