#!/usr/bin/env bash
# txwifi — Wi-Fi connection info with a signal-quality reading.
# Usage: txwifi [--json] [--watch SECONDS]
#   On Android uses termux-wifi-connectioninfo and turns the RSSI into a
#   0-100% quality bar with a plain-language verdict. On plain Linux
#   falls back to `iw`, `nmcli`, or /proc/net/wireless when available.
set -u
prog=txwifi

usage() {
  cat <<'USAGE'
Usage: txwifi [--json] [--watch SECONDS]
  Show the current Wi-Fi connection: SSID, BSSID, IP, link speed,
  band, and signal quality from the RSSI.
  --json        print the raw termux-wifi-connectioninfo JSON
  --watch N     reprint every N seconds until interrupted
  --selftest    run built-in checks (fake termux-api shim + guard)
  --help        show this help
  Android: termux-wifi-connectioninfo. Linux fallback: iw, nmcli, or
  /proc/net/wireless. If none is available it says so plainly.
USAGE
}

render_json() {
  if command -v python3 >/dev/null 2>&1; then
    python3 -c '
import json, sys
d = json.load(sys.stdin)
ssid = d.get("ssid", "?")
bssid = d.get("bssid", "?")
ip = d.get("ip", "?")
mac = d.get("mac_address", "?")
rssi = d.get("rssi")
speed = d.get("link_speed_mbps")
freq = d.get("frequency_mhz")
state = d.get("supplicant_state", "?")
if isinstance(rssi, (int, float)):
    q = max(0, min(100, 2 * (rssi + 100)))
    verdict = "excellent" if q >= 75 else "good" if q >= 50 else "fair" if q >= 25 else "poor"
    bars = "▂▄▆█"[0:0] + ("█" * (1 + q // 25)) + ("░" * (4 - (1 + q // 25))) if q > 0 else "░░░░"
    sig = "%s dBm (%d%%, %s) %s" % (rssi, q, verdict, bars)
else:
    sig = "unknown"
band = "?"
if isinstance(freq, (int, float)):
    band = "2.4 GHz" if freq < 3000 else "5 GHz" if freq < 6000 else "6 GHz"
print("Wi-Fi: %s (%s)" % (ssid, state))
print("  BSSID: %s   MAC: %s   IP: %s" % (bssid, mac, ip))
print("  signal: %s" % sig)
print("  link speed: %s Mbps   band: %s (%s MHz)" % (speed if speed is not None else "?", band, freq if freq is not None else "?"))
'
  else
    cat
    echo "note: install python3 for a human-readable summary" >&2
  fi
}

linux_fallback() {
  if command -v iw >/dev/null 2>&1; then
    local dev
    dev=$(iw dev 2>/dev/null | awk '/Interface/ {print $2; exit}')
    if [[ -n $dev ]]; then iw dev "$dev" link 2>/dev/null | sed 's/^/  /'; echo "Wi-Fi: interface $dev (via iw)"; return 0; fi
  fi
  if command -v nmcli >/dev/null 2>&1; then
    nmcli -t -f ACTIVE,SSID,SIGNAL,CHAN,RATE dev wifi 2>/dev/null | awk -F: '$1=="yes" {printf "Wi-Fi: %s  signal: %s%%  channel: %s  rate: %s (via nmcli)\n", $2, $3, $4, $5; found=1} END {exit !found}' && return 0
  fi
  if [[ -r /proc/net/wireless ]]; then
    awk 'NR>2 {gsub(/\./,"",$3); q=$3*100/70; printf "Wi-Fi: interface %s  signal quality: %.0f%% (via /proc/net/wireless)\n", $1, q}' /proc/net/wireless | head -n 5
    [[ -s /proc/net/wireless ]] && grep -q ':' /proc/net/wireless && return 0
  fi
  return 1
}

show_once() {
  local json=${1:-0}
  if command -v termux-wifi-connectioninfo >/dev/null 2>&1; then
    if (( json )); then termux-wifi-connectioninfo; return 0; fi
    termux-wifi-connectioninfo | render_json
    return 0
  fi
  if (( json )); then echo "$prog: termux-wifi-connectioninfo not available; no JSON source on plain Linux" >&2; fi
  linux_fallback || {
    printf '%s: termux-api not available (termux-wifi-connectioninfo not found) and no Linux Wi-Fi source found (iw, nmcli, /proc/net/wireless).\n' "$prog" >&2
    printf '%s: run this on Android with Termux:API installed, or on Linux with wireless-tools/NetworkManager.\n' "$prog" >&2
    return 1; }
}

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" "{\"bssid\":\"aa:bb:cc:dd:ee:ff\",\"frequency_mhz\":5180,\"ip\":\"192.168.1.42\",\"link_speed_mbps\":866,\"mac_address\":\"11:22:33:44:55:66\",\"network_id\":0,\"rssi\":-42,\"ssid\":\"HomeNet\",\"supplicant_state\":\"COMPLETED\"}"' > "$tmp/bin/termux-wifi-connectioninfo"
  chmod +x "$tmp/bin/termux-wifi-connectioninfo"
  out=$(PATH="$tmp/bin:$PATH" "$self" 2>&1); rc=$?
  if (( rc == 0 )) && [[ $out == *"HomeNet"* && $out == *"192.168.1.42"* && $out == *"5 GHz"* && $out == *"excellent"* ]]; then echo "PASS: termux path renders SSID/IP/band/quality"; else echo "FAIL: termux path rc=$rc out=$out"; fails=1; fi
  out=$(PATH="$tmp/bin:$PATH" "$self" --json 2>&1)
  if [[ $out == *'"ssid":"HomeNet"'* ]]; then echo "PASS: --json passthrough"; else echo "FAIL: --json out=$out"; fails=1; fi
  out=$(PATH="/usr/bin:/bin" "$self" 2>&1); rc=$?
  if (( rc != 0 )) && [[ $out == *"termux-api not available"* ]]; then echo "PASS: graceful degradation message (no Wi-Fi source on this box)"; 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 "txwifi selftest: all PASS" || echo "txwifi selftest: $fails FAILURES"
  return $fails
}

json=0 watch=0
while (( $# )); do
  case $1 in
    --help|-h) usage; exit 0;;
    --selftest) selftest; exit $?;;
    --json) json=1;;
    --watch) shift; watch=${1:?--watch needs seconds}; [[ $watch =~ ^[0-9]+$ ]] || { echo "$prog: --watch needs a number" >&2; exit 1; };;
    *) echo "$prog: unknown option: $1" >&2; usage >&2; exit 1;;
  esac
  shift
done
if (( watch > 0 )); then
  while true; do show_once "$json"; sleep "$watch"; done
else
  show_once "$json"
fi
