#!/bin/sh -e
#
# htmlbrowser - pipe html to a browser
#
# usage:
#     echo '<h1>hi mom!</h1>' | htmlbrowser
#     ron -5 man/rip.5.ron | htmlbrowser

progname=$(basename "$0")
tmp="${TMPDIR:-/tmp}/${progname}.${$}.$(awk \
  'BEGIN { srand(); printf "%d\n", rand() * 10^10 }')"

# remove tmpdir on exit
# trap 'rm -rf "$tmp"' 0
# trap 'exit 2' HUP QUIT INT TERM
# trap 'rm -f "$tmp"' EXIT HUP INT TERM
# rm -rf -- "${TMPDIR:-/tmp}"/htmlbrowser.*

if [ -t 0 ]; then
  if [ -n "$1" ]; then
    open "$1"
  else
    cat <<EOF
Usage: browser
       pipe html to a browser

  echo '<h1>hi mom!</h1>' | browser
  ron -5 man/rip.5.ron | browser
EOF
  fi
else
  mktemp "${tmp}"
  cat /dev/stdin >"${tmp}"
  trap 'exit 0' TERM INT
  # shellcheck disable=SC2064
  trap "rm -f ${tmp}" EXIT
  browser "${tmp}"
  sleep 1 &
  wait
fi
