#!/usr/bin/env bash
# txusb — list USB devices attached to the phone.
# Usage: txusb [--json]
#   Uses `termux-usb -l` when present (falling back to a
#   `termux-usb-list` command if that is what is installed) and prints
#   each device with vendor/product ids, manufacturer, product and
#   serial.
set -u
prog=txusb

usage() {
  cat <<'USAGE'
Usage: txusb [--json]
  List USB devices via termux-usb -l (or termux-usb-list).
  --json        print the raw JSON instead of the formatted list
  --selftest    run built-in checks (fake termux-api shim + guard)
  --help        show this help
  Requires termux-usb (Termux:API). No Linux equivalent exists, so on
  plain Linux this prints a clear message and exits non-zero.
USAGE
}

render() {
  if command -v python3 >/dev/null 2>&1; then
    python3 -c '
import json, sys
try:
    d = json.load(sys.stdin)
except Exception as e:
    print("txusb: could not parse USB list: %s" % e, file=sys.stderr)
    sys.exit(1)
if isinstance(d, dict):
    d = d.get("devices", [d])
if not d:
    print("no USB devices attached")
    sys.exit(0)
for dev in d:
    if not isinstance(dev, dict):
        print(dev)
        continue
    vid = dev.get("vendor_id"); pid = dev.get("product_id")
    ids = ""
    if vid is not None and pid is not None:
        ids = " [%04x:%04x]" % (int(vid), int(pid))
    name = dev.get("product_name") or dev.get("product") or dev.get("device_name") or "?"
    man = dev.get("manufacturer_name") or dev.get("manufacturer") or "?"
    serial = dev.get("serial") or ""
    print("%s%s — %s%s" % (name, ids, man, ("  serial: %s" % serial) if serial else ""))
print("(%d device%s)" % (len(d), "s" if len(d) != 1 else ""))
'
  else
    cat
    echo "note: install python3 for a formatted list" >&2
  fi
}

selftest() {
  local tmp fails=0 out rc
  tmp=$(mktemp -d); trap "rm -rf '$tmp'" EXIT
  local self="${BASH_SOURCE[0]}"
  mkdir -p "$tmp/bin"
  printf '%s\n' '#!/usr/bin/env bash' 'printf "%s" "[{\"device_name\":\"/dev/bus/usb/001/002\",\"vendor_id\":7531,\"product_id\":2,\"manufacturer_name\":\"SanDisk\",\"product_name\":\"Ultra Fit\",\"serial\":\"4C530001100823117372\"},{\"device_name\":\"/dev/bus/usb/001/003\",\"vendor_id\":1118,\"product_id\":1972,\"manufacturer_name\":\"Logitech\",\"product_name\":\"USB Receiver\"}]"' > "$tmp/bin/termux-usb"
  chmod +x "$tmp/bin/termux-usb"
  out=$(PATH="$tmp/bin:$PATH" "$self" 2>&1); rc=$?
  if (( rc == 0 )) && [[ $out == *"Ultra Fit"* && $out == *"[1d6b:0002]"* && $out == *"SanDisk"* && $out == *"(2 devices)"* ]]; then echo "PASS: termux-usb -l path renders devices"; else echo "FAIL: termux path rc=$rc out=$out"; fails=1; fi
  out=$(PATH="$tmp/bin:$PATH" "$self" --json 2>&1)
  if [[ $out == *'"product_name":"Ultra Fit"'* ]]; then echo "PASS: --json passthrough"; else echo "FAIL: --json out=$out"; fails=1; fi
  mkdir -p "$tmp/minbin"; ln -s /usr/bin/bash "$tmp/minbin/bash"
  out=$(PATH="$tmp/minbin" "$self" 2>&1); rc=$?
  if (( rc != 0 )) && [[ $out == *"termux-api not available"* ]]; then echo "PASS: graceful degradation message"; else echo "FAIL: guard rc=$rc out=$out"; fails=1; fi
  out=$("$self" --help 2>&1); rc=$?
  if (( rc == 0 )) && [[ $out == *"Usage:"* ]]; then echo "PASS: --help"; else echo "FAIL: --help rc=$rc"; fails=1; fi
  (( fails == 0 )) && echo "txusb selftest: all PASS" || echo "txusb selftest: $fails FAILURES"
  return $fails
}

asjson=0
while (( $# )); do
  case $1 in
    --help|-h) usage; exit 0;;
    --selftest) selftest; exit $?;;
    --json) asjson=1;;
    *) echo "$prog: unknown option: $1" >&2; usage >&2; exit 1;;
  esac
  shift
done
if command -v termux-usb >/dev/null 2>&1; then
  if (( asjson )); then termux-usb -l; else termux-usb -l | render; fi
  exit 0
fi
if command -v termux-usb-list >/dev/null 2>&1; then
  if (( asjson )); then termux-usb-list; else termux-usb-list | render; fi
  exit 0
fi
printf '%s: termux-api not available (termux-usb not found)\n' "$prog" >&2
printf '%s: run this on Android with Termux:API installed. There is no Linux equivalent for listing a phone%s USB devices.\n' "$prog" "’s" >&2
exit 1
