#!/usr/bin/env bash
# txtelephony — telephony and device info in one view.
# Usage: txtelephony [--json]
#   Reads termux-telephony-deviceinfo and prints the SIM state,
#   operator, network type, roaming/data state and device ids as a
#   labelled list instead of raw JSON.
set -u
prog=txtelephony

usage() {
  cat <<'USAGE'
Usage: txtelephony [--json]
  Show telephony and device info via termux-telephony-deviceinfo.
  --json        print the raw JSON instead of the labelled list
  --selftest    run built-in checks (fake termux-api shim + guard)
  --help        show this help
  Requires termux-telephony-deviceinfo (Termux:API); 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("txtelephony: could not parse device info: %s" % e, file=sys.stderr)
    sys.exit(1)
labels = {
    "device_id": "device id", "imei": "IMEI", "meid": "MEID",
    "sim_state": "SIM state", "sim_operator": "SIM operator",
    "network_operator": "network operator",
    "network_operator_name": "operator",
    "network_type": "network type", "phone_type": "phone type",
    "data_state": "data state", "roaming": "roaming",
    "signal_strength": "signal strength",
    "cell_info": "cell info", "mcc": "MCC", "mnc": "MNC",
}
shown = set()
for key in ("device_id", "imei", "sim_state", "network_operator_name", "network_operator", "network_type", "phone_type", "data_state", "roaming", "signal_strength"):
    if key in d:
        print("%-16s %s" % (labels.get(key, key) + ":", d[key]))
        shown.add(key)
for key in sorted(d.keys()):
    if key not in shown:
        v = d[key]
        if isinstance(v, (dict, list)):
            v = json.dumps(v)
        print("%-16s %s" % (labels.get(key, key) + ":", v))
'
  else
    cat
    echo "note: install python3 for a labelled 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" "{\"data_state\":\"DATA_CONNECTED\",\"device_id\":\"86753098675309\",\"network_operator\":\"310260\",\"network_operator_name\":\"T-Mobile\",\"network_type\":\"LTE\",\"phone_type\":\"GSM\",\"roaming\":false,\"sim_state\":\"SIM_STATE_READY\"}"' > "$tmp/bin/termux-telephony-deviceinfo"
  chmod +x "$tmp/bin/termux-telephony-deviceinfo"
  out=$(PATH="$tmp/bin:$PATH" "$self" 2>&1); rc=$?
  if (( rc == 0 )) && [[ $out == *"T-Mobile"* && $out == *"LTE"* && $out == *"SIM_STATE_READY"* && $out == *"DATA_CONNECTED"* ]]; then echo "PASS: termux path renders labelled info"; else echo "FAIL: termux path rc=$rc out=$out"; fails=1; fi
  out=$(PATH="$tmp/bin:$PATH" "$self" --json 2>&1)
  if [[ $out == *'"network_type":"LTE"'* ]]; 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"; 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 "txtelephony selftest: all PASS" || echo "txtelephony 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
command -v termux-telephony-deviceinfo >/dev/null 2>&1 || {
  printf '%s: termux-api not available (termux-telephony-deviceinfo not found)\n' "$prog" >&2
  printf '%s: run this on Android with Termux:API installed and phone permission granted.\n' "$prog" >&2
  exit 1; }
if (( asjson )); then termux-telephony-deviceinfo; else termux-telephony-deviceinfo | render; fi
