#!/usr/bin/env bash
# txvibrate — vibrate the device.
# Usage: txvibrate [DURATION_MS] [-f|--force] [--dry-run]
#   Wrapper around termux-vibrate. Default duration 200 ms. The -f flag
#   forces vibration even in silent mode, as termux-vibrate does.
set -u
prog=txvibrate

usage() {
  cat <<'USAGE'
Usage: txvibrate [DURATION_MS] [-f|--force] [--dry-run]
  Vibrate the device via termux-vibrate.
  DURATION_MS   vibration length in milliseconds, 1-10000 (default 200)
  -f, --force   vibrate even when the device is in silent mode
  --dry-run     print the termux-vibrate command, do not vibrate
  --selftest    run built-in checks (dry-run + guard only)
  --help        show this help
  Requires termux-vibrate (Termux:API). No Linux equivalent exists, so
  on plain Linux this prints a clear message and exits non-zero.
USAGE
}

selftest() {
  local tmp fails=0 out rc
  tmp=$(mktemp -d); trap "rm -rf '$tmp'" EXIT
  local self="${BASH_SOURCE[0]}"
  out=$("$self" --dry-run 500 -f 2>&1); rc=$?
  if (( rc == 0 )) && [[ $out == *"termux-vibrate"* && $out == *"-d 500"* && $out == *"-f"* ]]; then echo "PASS: --dry-run builds the command"; else echo "FAIL: dry-run rc=$rc out=$out"; fails=1; fi
  out=$("$self" --dry-run 0 2>&1); rc=$?
  if (( rc != 0 )); then echo "PASS: duration 0 rejected"; else echo "FAIL: duration 0 should fail"; fails=1; fi
  out=$("$self" --dry-run abc 2>&1); rc=$?
  if (( rc != 0 )); then echo "PASS: non-numeric duration rejected"; else echo "FAIL: bad duration should fail"; fails=1; fi
  out=$(PATH="/usr/bin:/bin" "$self" 500 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 "txvibrate selftest: all PASS" || echo "txvibrate selftest: $fails FAILURES"
  return $fails
}

dur=200 force=0 dryrun=0
while (( $# )); do
  case $1 in
    --help|-h) usage; exit 0;;
    --selftest) selftest; exit $?;;
    --dry-run) dryrun=1;;
    -f|--force) force=1;;
    --) shift; break;;
    -*) echo "$prog: unknown option: $1" >&2; usage >&2; exit 1;;
    *) dur=$1;;
  esac
  shift
done
[[ $dur =~ ^[0-9]+$ ]] && (( dur >= 1 && dur <= 10000 )) || { echo "$prog: duration must be 1-10000 ms, got '$dur'" >&2; exit 1; }
args=(-d "$dur"); (( force )) && args+=(-f)
if (( dryrun )); then printf 'termux-vibrate'; printf ' %q' "${args[@]}"; printf '\n'; exit 0; fi
command -v termux-vibrate >/dev/null 2>&1 || {
  printf '%s: termux-api not available (termux-vibrate not found)\n' "$prog" >&2
  printf '%s: run this on Android with Termux:API installed. There is no Linux equivalent for vibrating a phone.\n' "$prog" >&2
  exit 1; }
termux-vibrate "${args[@]}"
