#!/bin/sh
#
# This useful wrapper will call the command you pass it, but suppress
# any output to STDERR or STDOUT unless (a) the command exits in error
# (with a non-zero value) or (b) one of the signals SIGHUP, SIGINT,
# SIGQUIT or SIGTERM were sent.  This is particularly useful for
# wrapping commands invoked by cron, which will send an email if there
# is any output, whereas generally I only want to get an email if the
# command exited in error.

if [ "$#" -lt 1 ]; then
  cat >&2 <<EOF
Usage: $0 COMMAND [ARGUMENTS]...
EOF
  exit 1
fi

# safely create a temporary file to store the output in:
output="$(mktemp)"

# make sure that RESULT is initiallyset to an non-zero value so that
# if we get a signal, we can just call exit with $RESULT:
RESULT=1

# https://overflow.adminforge.de/questions/2175647/placeholder#2183063
# call trap for each signal we want to handle, passing in signal as an argument:
trap_with_arg() {
  func="$1"
  shift
  for signal; do
    trap '"${func} ${signal}"' "${signal}"
  done
}

# shellcheck disable=SC2329
on_signal() {
  echo "Error: exiting on receiving the signal $1"
  on_error
}

on_error() {
  cat "${output}"
  rm -f "${output}"
  exit "${RESULT}"
}

trap_with_arg on_signal HUP INT QUIT TERM

"$@" >"${output}" 2>&1

RESULT="$?"

if [ "${RESULT}" != 0 ]; then
  on_error
fi

rm -f "${output}"

exit "${RESULT}"
