#!/bin/sh
#
# quietrun - run command and only allow output if exit code didn't reflect success
#
# ---
# chronic (moreutils) does the same thing without temporary files
# see: https://git.kitenet.net/index.cgi/moreutils.git/tree/chronic
# source: https://github.com/aspiers/shell-env

tmpdir=/tmp/quietrun.$$
# half-heartedly guard against symlink attacks/accidents.
# there's still a race. does anyone actually care?
[ -e "${tmpdir}" ] && rm -rf "${tmpdir}"
if [ -e "${tmpdir}" ]; then
  echo "Couldn't remove ${tmpdir}; aborting."
  exit 1
fi
if ! mkdir "${tmpdir}"; then
  echo "Couldn't create ${tmpdir}; aborting."
  exit 1
fi

if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
  cat <<'EOF'
Usage: quietrun [ -m | --merge ] <command> [ <args> ... ]

If the merge option is specified, stdout and stderr are merged into
stdout, but the output order is preserved.  Otherwise they kept
separate, but output from stderr only appears after output from stdout.

The exit code from the command is preserved.
EOF
  exit 0
fi

if [ "$1" = "-m" ] || [ "$1" = "--merge" ]; then
  shift
  merge=yes
fi

if [ "$#" -eq 0 ]; then
  echo "quietrun: no command supplied"
  exit 1
fi

if [ "${merge}" = "yes" ]; then
  # shellcheck disable=SC2069
  "$@" 2>&1 >"${tmpdir}/both"
  exit_code="$?"
  if [ "${exit_code}" != 0 ]; then
    [ -e "${tmpdir}/both" ] && cat "${tmpdir}/both"
  fi
else
  "$@" >"${tmpdir}/stdout" 2>"${tmpdir}/stderr"
  exit_code="$?"
  if [ "${exit_code}" != 0 ]; then
    [ -e "${tmpdir}/stdout" ] && cat "${tmpdir}/stdout"
    [ -e "${tmpdir}/stderr" ] && cat "${tmpdir}/stderr" 1>&2 2>/dev/null
  fi
fi

rm -rf "${tmpdir}"

exit "${exit_code}"
