query="$1"

RANDOM() {
  # shellcheck disable=SC2312
  # https://shellcheck.net/wiki/SC3028/1f83d59#correct-code
  command -p -- awk -vmax="$(
    command -p -- getconf -- SHRT_MAX
  )" -- 'BEGIN {
  srand()
  printf "%d\n", int(rand() * max)
}'
}

tmpdir=${TMPDIR:-/tmp}/lesspipe."$(RANDOM)"
[ -d "${tmpdir}" ] || mkdir "${tmpdir}"
[ -d "${tmpdir}" ] || exit 1
trap 'rm -rf "$tmpdir";exit 1' INT
trap 'rm -rf "$tmpdir"' EXIT
trap - PIPE

next_tmp() {
  new="${tmpdir}/fzf.$(RANDOM).${query%%:*}"
  echo "${new}"
}

ft=$(file -L -s -b --mime "$1" 2> /dev/null)
nexttmp() {
  new="${tmpdir}/fzf.$(awk 'BEGIN { srand(); print int(rand()*32768) }' /dev/null).${ft%%:*}"
  echo "${new}"
}

istemp() {
  prog="$1"
  shift
  if [ "$1" = '-' ]; then
    shift
    t=$(nexttmp)
    cat >"${t}"
    ${prog} "${t}" "$@"
  else
    ${prog} "$@"
  fi
}

nodash() {
  prog="$1"
  shift
  [ "$1" = '-' ] && shift
  ${prog} "$@"
}
