#!/usr/bin/env bash
# txdownload — download a file into Downloads.
# Usage: txdownload [-o PATH] [--dry-run] URL...
#   Wraps termux-download (which saves into the Android Downloads
#   folder). On plain Linux falls back to curl into ~/Downloads, and
#   says so. Validates URLs before doing anything.
set -u
prog=txdownload
DL_DIR="${TXDOWNLOAD_DIR:-$HOME/Downloads}"

usage() {
  cat <<'USAGE'
Usage: txdownload [-o PATH] [--dry-run] URL...
  Download file(s) into Downloads via termux-download.
  -o PATH       save to this path instead of Downloads/<basename>
  --dry-run     print the termux-download command, do not download
  --selftest    run built-in checks (dry-run + validation + shim + curl)
  --help        show this help
  URLs must start with http:// or https:// (file:// is accepted only
  for the curl fallback, e.g. in tests). On Android this uses
  termux-download; on plain Linux it falls back to curl -L into
  ~/Downloads and says so.
USAGE
}

valid_url() { [[ $1 =~ ^https?://[^[:space:]]+$ ]] || [[ $1 =~ ^file://[^[:space:]]+$ ]]; }

selftest() {
  local tmp fails=0 out rc
  tmp=$(mktemp -d); trap "rm -rf '$tmp'" EXIT
  local self="${BASH_SOURCE[0]}"
  out=$("$self" --dry-run https://example.com/file.zip 2>&1); rc=$?
  if (( rc == 0 )) && [[ $out == *"termux-download"* && $out == *"https://example.com/file.zip"* ]]; then echo "PASS: --dry-run builds the command"; else echo "FAIL: dry-run rc=$rc out=$out"; fails=1; fi
  out=$("$self" --dry-run -o /tmp/out.bin https://example.com/f.bin 2>&1); rc=$?
  if (( rc == 0 )) && [[ $out == *"-o /tmp/out.bin"* ]]; then echo "PASS: --dry-run with -o"; else echo "FAIL: -o rc=$rc out=$out"; fails=1; fi
  out=$("$self" --dry-run notaurl 2>&1); rc=$?
  if (( rc != 0 )) && [[ $out == *"not a valid URL"* ]]; then echo "PASS: bad URL rejected"; else echo "FAIL: bad URL rc=$rc out=$out"; fails=1; fi
  out=$("$self" --dry-run 2>&1); rc=$?
  if (( rc != 0 )); then echo "PASS: no URL rejected"; else echo "FAIL: no-URL should fail"; fails=1; fi
  # fake termux-download shim records its arguments
  mkdir -p "$tmp/bin"
  printf '%s\n' '#!/usr/bin/env bash' 'printf "%s\n" "$@" >> "$TXDL_LOG"' > "$tmp/bin/termux-download"
  chmod +x "$tmp/bin/termux-download"
  : > "$tmp/log"
  out=$(TXDL_LOG="$tmp/log" PATH="$tmp/bin:$PATH" "$self" https://example.com/f.zip 2>&1); rc=$?
  if (( rc == 0 )) && grep -q 'https://example.com/f.zip' "$tmp/log"; then echo "PASS: termux-download path used on Android"; else echo "FAIL: shim rc=$rc out=$out log=$(cat "$tmp/log")"; fails=1; fi
  # curl fallback: file:// URL into a temp Downloads dir, no network
  printf 'fallback-content' > "$tmp/source.txt"
  out=$(TXDOWNLOAD_DIR="$tmp/dl" PATH="/usr/bin:/bin" "$self" "file://$tmp/source.txt" 2>&1); rc=$?
  if (( rc == 0 )) && [[ -f "$tmp/dl/source.txt" ]] && [[ $(cat "$tmp/dl/source.txt") == "fallback-content" ]]; then echo "PASS: curl fallback downloads to Downloads dir"; else echo "FAIL: curl fallback rc=$rc out=$out"; fails=1; fi
  # guard: neither termux-download nor curl
  mkdir -p "$tmp/minbin"; ln -s /usr/bin/bash "$tmp/minbin/bash"
  out=$(PATH="$tmp/minbin" "$self" https://example.com/f.zip 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 "txdownload selftest: all PASS" || echo "txdownload selftest: $fails FAILURES"
  return $fails
}

outpath="" dryrun=0 urls=()
while (( $# )); do
  case $1 in
    --help|-h) usage; exit 0;;
    --selftest) selftest; exit $?;;
    --dry-run) dryrun=1;;
    -o) shift; outpath=${1:?-o needs a value};;
    -*) echo "$prog: unknown option: $1" >&2; usage >&2; exit 1;;
    *) urls+=("$1");;
  esac
  shift
done
(( ${#urls[@]} )) || { echo "$prog: need at least one URL" >&2; usage >&2; exit 1; }
for u in "${urls[@]}"; do valid_url "$u" || { echo "$prog: not a valid URL: $u" >&2; exit 1; }; done
if command -v termux-download >/dev/null 2>&1; then
  args=()
  [[ -n $outpath ]] && args+=(-o "$outpath")
  args+=("${urls[@]}")
  if (( dryrun )); then printf 'termux-download'; printf ' %q' "${args[@]}"; printf '\n'; exit 0; fi
  termux-download "${args[@]}"
  exit 0
fi
if (( dryrun )); then
  printf '# termux-download not found; Linux fallback would run:\n'
  for u in "${urls[@]}"; do
    dest=${outpath:-$DL_DIR/${u##*/}}
    printf 'curl -L -o %q %q\n' "$dest" "$u"
  done
  exit 0
fi
command -v curl >/dev/null 2>&1 || {
  printf '%s: termux-api not available (termux-download not found) and no curl fallback.\n' "$prog" >&2
  printf '%s: run this on Android with Termux:API installed, or on Linux with curl.\n' "$prog" >&2
  exit 1; }
echo "$prog: termux-download not found; Linux fallback: downloading with curl into ${outpath:-$DL_DIR}" >&2
mkdir -p "${outpath:+$(dirname "$outpath")}" "$DL_DIR" 2>/dev/null
for u in "${urls[@]}"; do
  if [[ -n $outpath ]]; then dest=$outpath; else dest="$DL_DIR/${u##*/}"; fi
  [[ $dest == */ ]] && dest="${dest}$(basename "$u")"
  curl -L -o "$dest" "$u" || { echo "$prog: download failed: $u" >&2; exit 1; }
  echo "saved: $dest"
done
