#!/usr/bin/env bash
# txstorage — storage info: internal/external totals, free space, and
# whether Termux storage access is set up.
# Usage: txstorage [--json] [--path PATH]
#   On Android prefers termux-storage-info; falls back to df on both
#   Android and plain Linux, and reports on $HOME/storage.
set -u
prog=txstorage

usage() {
  cat <<'USAGE'
Usage: txstorage [--json] [--path PATH]
  Show storage usage: total / used / free for internal and external
  storage, plus whether Termux storage access ($HOME/storage) is set up.
  --path PATH   also report one extra path
  --json        print the raw termux-storage-info JSON when available
  --selftest    run built-in checks (fake termux-api shim + df fallback)
  --help        show this help
  On Android this uses termux-storage-info when present; otherwise it
  uses df, which also works on plain Linux.
USAGE
}

df_line() { # df_line PATH -> "PATH  total  used  avail  use%"
  local p=$1 total used avail pct
  read -r total used avail pct < <(df -B1 --output=size,used,avail,pcent "$p" 2>/dev/null | tail -n 1)
  [[ -n $total ]] || return 1
  printf '%-28s %12s %12s %12s %6s\n' "$p" "$(human "$total")" "$(human "$used")" "$(human "$avail")" "$pct"
}

human() { # human BYTES -> "12.3G" etc.
  local b=${1:-0}
  if command -v numfmt >/dev/null 2>&1; then numfmt --to=iec --format='%.1f' "$b" 2>/dev/null || printf '%s' "$b"; return 0; fi
  awk -v b="$b" 'BEGIN { u[0]="B"; u[1]="K"; u[2]="M"; u[3]="G"; u[4]="T"; i=0; while (b>=1024 && i<4) { b/=1024; i++ } printf "%.1f%s", b, u[i] }'
}

render_termux_json() {
  if command -v python3 >/dev/null 2>&1; then
    python3 -c '
import json, sys
d = json.load(sys.stdin)
def show(name, e):
    if not isinstance(e, dict):
        return
    total = e.get("bytes_total") or e.get("total")
    free = e.get("bytes_free") or e.get("free")
    if total is None:
        return
    used = total - (free or 0)
    pct = 100.0 * used / total if total else 0
    print("%-28s %12.1fG %12.1fG %12.1fG %5.0f%%" % (name, total/1e9, used/1e9, (free or 0)/1e9, pct))
print("%-28s %12s %12s %12s %6s" % ("storage", "total", "used", "free", "use%"))
for k in ("internal", "external"):
    if k in d:
        show(k, d[k])
for k, v in d.items():
    if k not in ("internal", "external"):
        show(k, v)
'
  else
    cat
    echo "note: install python3 for a formatted table" >&2
  fi
}

show_df() {
  local extra=${1:-}
  printf '%-28s %12s %12s %12s %6s\n' "path" "total" "used" "free" "use%"
  local p ok=0
  for p in "$HOME" /storage/emulated/0 /sdcard /data ${PREFIX:-}; do
    [[ -d $p ]] || continue
    df_line "$p" && ok=1
  done
  [[ -n $extra ]] && df_line "$extra"
  (( ok )) || { echo "$prog: no readable storage path found" >&2; return 1; }
  return 0
}

storage_setup_note() {
  if [[ -n ${PREFIX:-} && -d $HOME/storage ]]; then
    echo "Termux storage access: set up ($HOME/storage exists; run termux-setup-storage to redo it)"
  elif [[ -n ${PREFIX:-} ]]; then
    echo "Termux storage access: NOT set up — run 'termux-setup-storage' to expose shared storage at \$HOME/storage"
  else
    echo "Termux storage access: n/a (not running under Termux)"
  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" "{\"internal\":{\"bytes_total\":64000000000,\"bytes_free\":16000000000},\"external\":{\"bytes_total\":128000000000,\"bytes_free\":64000000000}}"' > "$tmp/bin/termux-storage-info"
  chmod +x "$tmp/bin/termux-storage-info"
  out=$(PATH="$tmp/bin:$PATH" "$self" 2>&1); rc=$?
  if (( rc == 0 )) && [[ $out == *"internal"* && $out == *"75%"* ]]; then echo "PASS: termux-storage-info path"; else echo "FAIL: termux path rc=$rc out=$out"; fails=1; fi
  out=$(PATH="$tmp/bin:$PATH" "$self" --json 2>&1)
  if [[ $out == *'"bytes_total":64000000000'* ]]; 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 == *"$HOME"* && $out == *"total"* ]]; then echo "PASS: df fallback on plain Linux"; else echo "FAIL: df fallback 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 "txstorage selftest: all PASS" || echo "txstorage selftest: $fails FAILURES"
  return $fails
}

json=0 extra=""
while (( $# )); do
  case $1 in
    --help|-h) usage; exit 0;;
    --selftest) selftest; exit $?;;
    --json) json=1;;
    --path) shift; extra=${1:?--path needs a value};;
    *) echo "$prog: unknown option: $1" >&2; usage >&2; exit 1;;
  esac
  shift
done
if command -v termux-storage-info >/dev/null 2>&1; then
  if (( json )); then termux-storage-info; exit 0; fi
  termux-storage-info | render_termux_json
  [[ -n $extra ]] && df_line "$extra"
  storage_setup_note
  exit 0
fi
if (( json )); then
  echo "$prog: termux-storage-info not available; no JSON source on plain Linux (use df output instead)" >&2
  show_df "$extra"; exit 0
fi
show_df "$extra"
storage_setup_note
