#!/usr/bin/env bash
# txvolume — show and set volume levels per stream.
# Usage: txvolume [STREAM] [LEVEL|up|down] [--json]
#   With no arguments prints every stream's current volume (from
#   termux-volume). With a stream and level it sets that stream.
#   Streams: alarm, music, notification, ring, system, call.
set -u
prog=txvolume

usage() {
  cat <<'USAGE'
Usage: txvolume [STREAM] [LEVEL|up|down] [--json]
  Show and set Android volume levels via termux-volume.
  (no args)        show all streams with a bar per stream
  STREAM           show one stream, e.g. txvolume music
  STREAM LEVEL     set a stream, e.g. txvolume music 8 (0-15)
  STREAM up|down   step a stream by 1 (from its current volume)
  --json           print the raw termux-volume JSON
  --selftest       run built-in checks (fake termux-api shim + guard)
  --help           show this help
  Streams: alarm, music, notification, ring, system, call.
  Requires termux-volume (Termux:API). No Linux equivalent exists, so
  on plain Linux this prints a clear message and exits non-zero.
USAGE
}

render_json() { # render_json [STREAM] -- reads termux-volume JSON on stdin
  local want=${1:-}
  if command -v python3 >/dev/null 2>&1; then
    TXVOLUME_WANT="$want" python3 -c '
import json, os, sys
want = os.environ.get("TXVOLUME_WANT", "")
try:
    d = json.load(sys.stdin)
except Exception as e:
    print("txvolume: could not parse volume info: %s" % e, file=sys.stderr)
    sys.exit(1)
if isinstance(d, list):
    d = {x.get("stream", "?"): x for x in d if isinstance(x, dict)}
def bar(vol, mx):
    if not mx:
        return ""
    w = 15
    f = max(0, min(w, vol * w // mx))
    return "█" * f + "░" * (w - f)
names = [want] if want else sorted(d.keys())
for name in names:
    info = d.get(name)
    if info is None:
        print("stream %r not found (try: %s)" % (name, ", ".join(sorted(d.keys()))))
        continue
    vol = info.get("volume", "?")
    mx = info.get("max_volume", 0)
    print("%-13s %2s/%-2s [%s]" % (name, vol, mx if mx else "?", bar(vol, mx) if isinstance(vol, int) else ""))
'
  else
    cat
    echo "note: install python3 for a formatted table" >&2
  fi
}

current_volume() { # current_volume STREAM -> current volume or empty
  termux-volume 2>/dev/null | python3 -c '
import json, sys
want = sys.argv[1]
try:
    d = json.load(sys.stdin)
except Exception:
    sys.exit(1)
if isinstance(d, list):
    d = {x.get("stream"): x for x in d if isinstance(x, dict)}
info = d.get(want)
print(info.get("volume", "") if isinstance(info, dict) else "")
' "$1" 2>/dev/null
}

selftest() {
  local tmp fails=0 out rc
  tmp=$(mktemp -d); trap "rm -rf '$tmp'" EXIT
  local self="${BASH_SOURCE[0]}"
  mkdir -p "$tmp/bin"
  cat > "$tmp/bin/termux-volume" <<'SH'
#!/usr/bin/env bash
if (( $# )); then printf 'SET %s %s\n' "$1" "$2" >> "$TXVOLUME_LOG"; exit 0; fi
printf '%s' '[{"stream":"music","volume":8,"max_volume":15},{"stream":"ring","volume":5,"max_volume":7},{"stream":"alarm","volume":6,"max_volume":7}]'
SH
  chmod +x "$tmp/bin/termux-volume"
  : > "$tmp/log"
  out=$(TXVOLUME_LOG="$tmp/log" PATH="$tmp/bin:$PATH" "$self" 2>&1); rc=$?
  if (( rc == 0 )) && [[ $out == *"music"* && $out == *"8/15"* ]]; then echo "PASS: show all streams"; else echo "FAIL: show rc=$rc out=$out"; fails=1; fi
  out=$(TXVOLUME_LOG="$tmp/log" PATH="$tmp/bin:$PATH" "$self" music 2>&1); rc=$?
  if (( rc == 0 )) && [[ $out == *"music"* && $out != *"ring"* ]]; then echo "PASS: show one stream"; else echo "FAIL: one stream rc=$rc out=$out"; fails=1; fi
  out=$(TXVOLUME_LOG="$tmp/log" PATH="$tmp/bin:$PATH" "$self" music 10 2>&1); rc=$?
  if (( rc == 0 )) && grep -q 'SET music 10' "$tmp/log"; then echo "PASS: set a stream"; else echo "FAIL: set rc=$rc out=$out log=$(cat "$tmp/log")"; fails=1; fi
  out=$(TXVOLUME_LOG="$tmp/log" PATH="$tmp/bin:$PATH" "$self" bogus 2>&1); rc=$?
  if (( rc != 0 )); then echo "PASS: bad stream rejected"; else echo "FAIL: bad stream should fail"; fails=1; fi
  out=$(TXVOLUME_LOG="$tmp/log" PATH="$tmp/bin:$PATH" "$self" music 99 2>&1); rc=$?
  if (( rc != 0 )); then echo "PASS: out-of-range level rejected"; else echo "FAIL: level 99 should fail"; 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 "txvolume selftest: all PASS" || echo "txvolume selftest: $fails FAILURES"
  return $fails
}

stream="" level="" 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;;
    *) if [[ -z $stream ]]; then stream=$1; elif [[ -z $level ]]; then level=$1; else echo "$prog: unexpected argument: $1" >&2; exit 1; fi;;
  esac
  shift
done
command -v termux-volume >/dev/null 2>&1 || {
  printf '%s: termux-api not available (termux-volume not found)\n' "$prog" >&2
  printf '%s: run this on Android with Termux:API installed. There is no Linux equivalent for Android audio streams.\n' "$prog" >&2
  exit 1; }
case $stream in ""|alarm|music|notification|ring|system|call) ;; *) echo "$prog: unknown stream '$stream' (alarm|music|notification|ring|system|call)" >&2; exit 1;; esac
if (( asjson )); then termux-volume; exit 0; fi
if [[ -z $stream ]]; then termux-volume | render_json; exit 0; fi
if [[ -z $level ]]; then termux-volume | render_json "$stream"; exit 0; fi
case $level in
  up|down)
    cur=$(current_volume "$stream")
    [[ $cur =~ ^[0-9]+$ ]] || { echo "$prog: could not read current volume for '$stream'" >&2; exit 1; }
    if [[ $level == up ]]; then level=$(( cur + 1 )); else level=$(( cur - 1 )); fi;;
esac
[[ $level =~ ^[0-9]+$ ]] && (( level <= 15 )) || { echo "$prog: level must be 0-15, got '$level'" >&2; exit 1; }
termux-volume "$stream" "$level"
echo "$stream volume set to $level"
