#!/bin/sh
#
# oii - run a command on input only if there's at least one byte of input
#
# Usage:
#      oii CMD [ARGS ...] < file
#      program | oii CMD [ARGS ...]

self=oii

# Need at least a command name
if [ "$#" -eq 0 ]; then
  printf >&2 '%s: Need a command\n' "${self}"
  exit 2
fi

# create a temporary directory with name in $td,
# and handle POSIX-ish traps to remove it when the script exits.
td=
cleanup() {
  [ -n "${td}" ] && rm -fr -- "${td}"
  if [ "$1" != EXIT ]; then
    trap - "$1"
    kill "-$1" "$$"
  fi
}
for sig in EXIT HUP INT TERM; do
  # shellcheck disable=SC2064
  trap "cleanup $sig" "$sig"
done
td=$(mktd "${self}") || exit

# Read up to one byte and save it into temp file; discard stderr (stats)
tf=${td}/input
dd bs=1 count=1 of="${tf}" 2>/dev/null

# If there's now a byte in the file, spit it and the rest of the input into the
# requested command
[ -s "${tf}" ] && cat -- "$tf" - | "$@"
