# func_exit STATUS
# exits with a given status
# this function needs to be used, rather than 'exit',
# when a 'trap' handler is in effect that refers to $?.
func_exit() {
  (exit "$1")
  exit "$1"
}

# func_tmpdir
# creates a temporary directory
# Input:
# - progname                 name of this program
# Sets variable
# - tmp             pathname of freshly created temporary directory
func_tmpdir() {
  : "${TMPDIR=/tmp}"
  {
    # use mktemp if available. if not available, hide error message
    tmp=$( (umask 077 && mktemp -d "${TMPDIR}/glXXXXXX") 2>/dev/null) \
      && test -n "${tmp}" && test -d "${tmp}"
  } \
    || {
      # Use a simple mkdir command. It is guaranteed to fail if the directory
      # already exists.  $RANDOM is bash specific and expands to empty in shells
      # other than bash, ksh and zsh.  Its use does not increase security;
      # rather, it minimizes the probability of failure in a very cluttered /tmp
      # directory.
      tmp=${TMPDIR}/gl$$-"${RANDOM}"
      (umask 077 && mkdir "${tmp}")
    } \
    || {
      echo "$(basename "$0"): cannot create a temporary directory in ${TMPDIR}" >&2
      func_exit 1
    }
}

func_tmpdir
# shellcheck disable=SC2154
trap 'exit_status=$?
      if test "$signal" != EXIT; then
        echo "caught signal SIG$signal" >&2
      fi
      rm -rf "$tmp"
      exit $exit_status' EXIT
for signal in HUP INT QUIT PIPE TERM; do
  # shellcheck disable=SC2248
  trap '{ signal='$signal'; func_exit 1; }' "$signal"
done
signal=EXIT

rm -rf "${tmp}"
# Undo the effect of the previous 'trap' command. Some shellology:
# We cannot use "trap - EXIT HUP INT QUIT PIPE TERM", because Solaris sh would
# attempt to execute the command "-". "trap '' ..." is fine only for signal EXIT
# (= normal exit); for the others we need to call 'exit' explicitly. The value
# of $? is 128 + signal number and is set before the trap-registered command is
# run.
trap '' EXIT
trap 'func_exit $?' HUP INT QUIT PIPE TERM

exit 0
