#!/usr/bin/env bash

# Cronic v2 - cron job report wrapper
# Copyright 2007 Chuck Houpt
# Documentation at http://habilis.net/cronic/
# In brief:
#   Cronic is a small shim shell script for wrapping cron jobs so that cron
#   only sends email when an error has occurred. Cronic defines an error as
#   any non-trace error output or a non-zero result code. Cronic separates
#   execution traces from the error output, so jobs can be run with execution
#   tracing to aid forensic debugging. Apart from its options, Cronic simply
#   executes its arguments.
#
# Extended by Michael Ernst to add the --expected-status, --permit-stderr, and
# --duplicate-stderr options, which may be given in any order.
#
# For usage information, run `cronic --help`.
#
# Names that start with `cronic_` are reserved for this script:  COMMAND does
# not see a variable or function with such a name, even one that the caller
# exported.  This script assumes that bash has the `compgen` builtin, which is
# absent only if bash was built with `--disable-progcomp`.
#
# Limitations, which `cronic --help` documents:  every run produces output if
# the caller exports the verbose option or runs `bash -v cronic`, or if the file
# named by BASH_ENV writes to stderr.  COMMAND does not see a function named
# `builtin` that the caller exported, because this script removes it so that it
# can run builtins via `builtin`.  If COMMAND starts a background process that
# keeps its stderr open, the report omits what that process writes to stderr
# more than 5 seconds after COMMAND exits.  If COMMAND reopens its standard
# output with truncation, as `> /dev/stdout` does on Linux, the report's
# combined standard and error output omits the output that COMMAND wrote before
# then, although the report still shows the error output by itself.

# This script runs under the first `bash` in PATH, which on macOS may be
# /bin/bash, bash 3.2.  So it uses a feature of a later bash, such as
# BASH_XTRACEFD (bash 4.1), only after checking the version; see the
# BASH_VERSINFO check below.

# Save the caller's settings of the options that this script changes, as the
# letters that `$-` uses for them, so that the command runs with them.  They
# include any option that BASH_ENV set, because bash runs BASH_ENV before this
# script's first line.  The command inherits every other option, including
# every `shopt` option, unchanged.  If this script ever changes another option,
# add its letter here.  Posix mode, which has no letter, is saved in
# `cronic_caller_posix`, which is non-empty if the caller's shell was in posix
# mode.
#
# Then turn on posix mode, by assigning POSIXLY_CORRECT, so that a special
# builtin, such as `export`, `set`, or `unset`, runs in place of a function of
# the same name that the caller exported.  Then turn off xtrace, so that this
# script does not trace itself to stderr, which would make every run produce
# output, and allexport, so that this script does not export its variables to
# the command.  The variables assigned before that are un-exported explicitly,
# or, for POSIXLY_CORRECT, unset below.  The redirection discards the trace of
# this block.  If the caller exports BASH_XTRACEFD, then bash writes that trace
# to the caller's trace descriptor instead.  If that descriptor is not open,
# then bash reports so on stderr before this script runs, as for any bash
# script; cronic cannot prevent that.
{
  cronic_caller_flags=${-//[^aeux]/}
  if [[ :$SHELLOPTS: == *:posix:* ]]; then
    cronic_caller_posix=y
  else
    cronic_caller_posix=
    POSIXLY_CORRECT=y
  fi
  set +ax
  export -n cronic_caller_flags cronic_caller_posix
} 2> /dev/null

# The next command removes every alias, such as one that BASH_ENV defined, so
# that no alias changes this script's commands or the caller's functions, which
# the command gets back by re-parsing their definitions; the backslash stops an
# alias named `unalias` from applying.  Bash imports the caller's exported
# functions before it runs BASH_ENV, so their bodies never contain an alias.
# The commands after it save the definitions of the caller's exported
# functions, which bash has imported, and remove every function, including any
# that BASH_ENV defined, so that none runs in place of a builtin or program that
# this script uses.  The command gets the exported functions back.  In posix
# mode, `export -pf` lists the names of the exported functions.  Once any
# function named `builtin` is removed, `builtin` runs the other builtins.
# `declare -f` runs with posix mode off, because posix mode rejects a function
# name, such as `my-fn`, that is not an identifier.  Unsetting POSIXLY_CORRECT
# turns posix mode off again, unless the caller's shell was already in posix
# mode, before the loop that removes the functions, because in posix mode bash
# 3.2 also rejects such a name in `unset -f`.  The loop runs `unset` and
# `exit` via `builtin`, so that no function runs in their place.  Their error
# output is not discarded:  if `unset` cannot remove a function, such as one
# that BASH_ENV made readonly, then bash reports the error and this script
# exits, so cron sends email rather than failing silently.
\unalias -a
cronic_exported=$(export -pf)
unset -f builtin
cronic_caller_functions=
cronic_caller_function_names=
while builtin read -r cronic_name; do
  cronic_name=${cronic_name#export -f }
  if [[ -n $cronic_name && $cronic_name != cronic_* && $cronic_name != builtin ]]; then
    builtin printf -v cronic_name_quoted ' %q' "$cronic_name"
    cronic_caller_function_names+=$cronic_name_quoted
  fi
done <<< "$cronic_exported"
if [[ -n $cronic_caller_function_names ]]; then
  cronic_caller_functions=$(unset POSIXLY_CORRECT; builtin eval "builtin declare -f --$cronic_caller_function_names") || :
fi
[[ -n $cronic_caller_posix ]] || unset POSIXLY_CORRECT
while builtin read -r cronic_name; do
  [[ -z $cronic_name ]] || builtin unset -f -- "$cronic_name" || builtin exit 1
done <<< "$(builtin compgen -A function)"

# Exit if a command exits with a non-zero status, and treat unset variables
# as an error.
set -eu

# Prints the usage line.
cronic_usage_line() {
  echo "Usage: $0 [--expected-status N] [--permit-stderr] [--duplicate-stderr] [--] COMMAND [ARG...]"
}

# Exits with status 64 (EX_USAGE in sysexits.h) rather than the conventional 2,
# because a wrapped command is much more likely to exit with status 2, and a
# caller that checks for a particular status should not mistake a misuse of
# this script for the command's own result.
cronic_usage() {
  cronic_usage_line >&2
  exit 64
}

# Prints a usage message to standard output and exits with status 0.
cronic_help() {
  cronic_usage_line
  echo "Runs COMMAND, and produces output only if it fails or writes to stderr."
  echo "The output is a report that shows the error output, and then, if COMMAND"
  echo "wrote to stdout, the standard and error output together, in the order in"
  echo "which COMMAND wrote them.  That order is approximate:  an error line written"
  echo "just before a line of standard output can appear after it.  And if COMMAND"
  echo "buffers its standard output, as many programs do when it is not a terminal,"
  echo "then that output appears when COMMAND flushes it, not when COMMAND wrote it."
  echo "  --expected-status N  treat exit status N (0 to 255), rather than 0, as success;"
  echo "                       may also be written --expected-status=N"
  echo "  --permit-stderr      do not treat error output as a failure"
  echo "  --duplicate-stderr   print the error output twice in the report, so that it"
  echo "                       is less likely to be overlooked"
  echo "  --                   end the options, so that COMMAND may start with \"-\""
  echo "  -h, --help           print this message"
  echo "COMMAND may be a program, a shell builtin, or a shell function that the"
  echo "caller exported; a function runs in place of a program of the same name."
  echo "Names that start with \"cronic_\" are reserved:  COMMAND does not see a"
  echo "variable or function with such a name, even one that the caller exported."
  echo "Nor does COMMAND see a function named \"builtin\" that the caller exported,"
  echo "because cronic removes it so that it can run builtins via \"builtin\"."
  echo "COMMAND runs with the caller's shell options, such as errexit, nounset,"
  echo "and xtrace (including any that BASH_ENV sets), rather than with this"
  echo "script's.  This script never traces itself, so \"bash -x cronic COMMAND\""
  echo "traces only the running of COMMAND."
  echo "Execution traces (from \"set -x\") are not treated as error output."
  echo "If the caller exports xtrace via SHELLOPTS, bash 4.1 or later writes them"
  echo "to a separate file, via BASH_XTRACEFD; they appear in the report under"
  echo "\"TRACE OUTPUT\".  Otherwise, BASH_XTRACEFD is not exported to COMMAND,"
  echo "because a bash started by a program that closes the inherited descriptor,"
  echo "such as Gradle, would report an error.  Then, and in other shells, traces"
  echo "go to stderr, from which lines that start with PS4 are removed.  That removal"
  echo "is skipped if PS4 contains \"\$\", a backquote, a backslash, or a newline,"
  echo "because such a PS4 can expand differently on each line."
  echo "If the caller's xtrace is on, cronic's own trace of running COMMAND is"
  echo "removed from the TRACE OUTPUT; that works only if PS4 contains no newline."
  echo "Do not run \"bash -v cronic\", nor export the verbose option (\"set -v\") via"
  echo "SHELLOPTS: bash would echo the lines of this script (and, if exported, of a"
  echo "bash COMMAND) to stderr, so every run would produce output."
  echo "Bash runs the file named by BASH_ENV, if any, before cronic's own code, so"
  echo "cronic cannot capture that file's output, and exported shell options can make"
  echo "that file write to stderr.  To prevent that, unset BASH_ENV."
  echo "If COMMAND starts a background process that keeps COMMAND's stderr open,"
  echo "cronic waits up to 5 seconds after COMMAND exits for that process to close"
  echo "it, and the report omits what that process writes to stderr after then."
  echo "If COMMAND reopens its standard output with truncation, as \`> /dev/stdout\`"
  echo "does on Linux, the standard and error output together omit what COMMAND"
  echo "wrote before then; the report still shows the error output by itself."
  exit 0
}

# Sets cronic_expected to its argument, or reports a usage error if the
# argument is not a valid exit status.
cronic_set_expected() {
  cronic_expected=$1
  # No leading zeros, because `[[ ... -eq ... ]]` would read the value as
  # octal.  At most 255, because no exit status is larger.
  if ! [[ $cronic_expected =~ ^(0|[1-9][0-9]{0,2})$ ]] || [ "$cronic_expected" -gt 255 ]; then
    echo "$0: --expected-status requires an integer from 0 to 255, got \"$cronic_expected\"" >&2
    cronic_usage
  fi
}

# The options are parsed before the temporary directory is created, so that
# `--help` and a usage error neither create nor depend on it.
cronic_expected=0
cronic_permitstderr=0
cronic_duplicate_stderr=0
while [ $# -gt 0 ]; do
  case $1 in
    --expected-status)
      shift
      if [ $# -eq 0 ]; then
        echo "$0: --expected-status requires a value" >&2
        cronic_usage
      fi
      cronic_set_expected "$1"
      shift
      ;;
    --expected-status=*)
      cronic_set_expected "${1#*=}"
      shift
      ;;
    --permit-stderr)
      shift
      cronic_permitstderr=1
      ;;
    --duplicate-stderr)
      shift
      cronic_duplicate_stderr=1
      ;;
    -h | --help)
      cronic_help
      ;;
    --)
      shift
      break
      ;;
    -*)
      echo "$0: unknown option \"$1\"" >&2
      cronic_usage
      ;;
    *)
      break
      ;;
  esac
done
[ $# -gt 0 ] || cronic_usage

cronic_debug=false
# cronic_debug=true

# A private directory, rather than predictable `/tmp/cronic.*.$$` names: on a
# shared machine, process ids are guessable and reused, so another user could
# pre-create those paths as symlinks and have the wrapped command's output
# written through them.
cronic_tmpdir=$(mktemp -d "${TMPDIR:-/tmp}/cronic.XXXXXX") || exit 1
cronic_combined=$cronic_tmpdir/combined
cronic_stderr_fifo=$cronic_tmpdir/stderr.fifo
cronic_tee_err=$cronic_tmpdir/tee.err
cronic_err=$cronic_tmpdir/err
cronic_reduced_err=$cronic_tmpdir/err.reduced
cronic_trace=$cronic_tmpdir/trace
cronic_xtrace=$cronic_tmpdir/xtrace
# The process id of the `tee` that copies the command's stderr, or empty if
# `tee` has not started or has been stopped.
cronic_tee_pid=

# Replaces the `tee` that copies the command's stderr, if it is still running,
# by a process that reads the FIFO and discards what it reads, so that the
# temporary files stop growing.  The FIFO always has a reader, so a background
# process that writes to its stderr does not get SIGPIPE:  this shell holds the
# FIFO open for reading from before the new reader starts until after `tee` is
# killed.  Opening the FIFO only for reading blocks until some process holds it
# open for writing, so this shell first opens it for both reading and writing,
# which does not block.  The new reader's descriptor is opened only for reading,
# because a reader that also held the FIFO open for writing would never read
# end-of-file and would never finish.  `tee` ignores the signals that this shell
# handles, so it is killed by SIGKILL.
cronic_stop_tee() {
  if [ -n "$cronic_tee_pid" ] && kill -0 "$cronic_tee_pid" 2> /dev/null; then
    exec 3<> "$cronic_stderr_fifo"
    exec 4< "$cronic_stderr_fifo"
    exec 3>&-
    (
      trap '' HUP INT TERM
      exec cat > /dev/null
    ) <&4 4<&- 2> /dev/null &
    kill -s KILL "$cronic_tee_pid" 2> /dev/null || :
    exec 4<&-
  fi
  cronic_tee_pid=
}

# Remove the temporary files however this script terminates, including when it
# is interrupted before it reaches the end.  When cronic_debug is true, the
# files are retained; don't "echo" their location, because that would be
# appended to stderr.
# shellcheck disable=SC2329  # the function is invoked from the trap handlers below.
cronic_cleanup() {
  cronic_stop_tee
  [ "$cronic_debug" = "true" ] || rm -rf "$cronic_tmpdir"
}
trap cronic_cleanup EXIT

# Clean up and then die of the signal, rather than exiting with status
# 128+signum, so that a supervisor can distinguish "cronic was killed by
# SIGTERM" from "the wrapped command exited with status 143".  Each handler
# first removes itself and the EXIT trap, so that the cleanup runs exactly
# once.  These handlers are not redundant with the EXIT trap:  with no handler
# installed, bash dies as soon as the signal arrives, abandoning the wrapped
# command and deleting the directory that the command is still writing into,
# whereas a handler does not run until the wrapped command has finished.
trap 'cronic_cleanup; trap - HUP EXIT; kill -s HUP $$' HUP
trap 'cronic_cleanup; trap - INT EXIT; kill -s INT $$' INT
trap 'cronic_cleanup; trap - TERM EXIT; kill -s TERM $$' TERM

# A bash command writes its execution trace to the file descriptor named by
# BASH_XTRACEFD, rather than to stderr, so the trace is separated from the
# error output exactly, whatever PS4 is.  The descriptor is allocated by bash
# (as 10 or higher), so that it does not collide with a descriptor, such as 3,
# that the wrapped command uses for its own purposes.  Bash before 4.1 supports
# neither BASH_XTRACEFD nor descriptor allocation.
#
# BASH_XTRACEFD is exported only if the caller exported xtrace, via SHELLOPTS,
# because only then is the command's trace expected.  Otherwise, it is
# un-exported, even if the caller exported it.  A program such as Gradle, or
# any other Java program, closes every descriptor above 2 when it starts a
# process.  A bash that such a program starts, even one that does no tracing,
# would get an exported BASH_XTRACEFD that names a closed descriptor, and would
# report so on stderr.  Unexported, BASH_XTRACEFD still applies to a builtin
# or exported function that is the command, which runs in this shell's subshell.
if ((BASH_VERSINFO[0] > 4 || (BASH_VERSINFO[0] == 4 && BASH_VERSINFO[1] >= 1))); then
  exec {cronic_xtrace_fd}> "$cronic_xtrace"
  BASH_XTRACEFD=$cronic_xtrace_fd
  if [[ $cronic_caller_flags == *x* && $(declare -p SHELLOPTS) =~ ^declare\ -[a-zA-Z]*x ]]; then
    export BASH_XTRACEFD
  else
    export -n BASH_XTRACEFD
  fi
fi

# The command runs in a subshell rather than via `exec`, so that it can be a
# shell builtin or an exported shell function, and rather than in this shell,
# so that a builtin such as `exit` or `exec` cannot end this script before it
# reports.
#
# The subshell unsets this script's functions, which are the only ones that
# remain, and every variable whose name starts with `cronic_`, so that the
# command does not see them, and so that a function does not run in place of a
# program of the same name.  The names of this script's functions are
# identifiers, so they need no quoting.  The `eval` expands the cronic_*
# variables before `unset` removes them.  If `unset` cannot remove one, such as
# one that BASH_ENV made readonly, then the subshell exits without running the
# command, and the report shows the error.  The `eval` then defines the caller's
# functions, which can replace a builtin, so the remaining commands run via
# `builtin`.
#
# The last command of the `eval` restores the caller's options that this script
# changed.  Otherwise, if the caller exported SHELLOPTS, a bash script that
# reads an unset variable (as `/usr/bin/texi2dvi` does when /bin/sh is bash)
# would fail.  Of those options, only nounset is on here, so a single `set`
# command turns it off and turns on the caller's, so that the restoring is not
# traced.  The `:+` avoids a bare `-`, which has a special meaning to `set`.
#
# The redirections apply to the whole subshell, so that they also capture what
# it writes after the command finishes, such as the output of an EXIT trap that
# the command sets.
#
# The report shows the standard output and the error output together, in the
# order in which the command wrote them, and it also shows the error output by
# itself.  So the subshell's standard output is appended to the file
# cronic_combined, and its stderr goes, through a FIFO, to `tee`, which writes
# it to the file cronic_trace and appends it to cronic_combined.  Both the
# subshell and `tee` open cronic_combined for appending, so that neither
# overwrites what the other wrote.  The order is exact only for writes that are
# separated in time:  an error line that immediately precedes a line of
# standard output can be appended after it, because the error line passes
# through `tee`.  Exact order is impossible, because only a single file
# descriptor for both streams would preserve it, and then `cronic` could not
# tell which output was error output.
#
# A command that reopens its standard output with truncation, as
# `> /dev/stdout` or `tee /dev/stdout` does on Linux, truncates cronic_combined,
# erasing the error output stored there.  The file cronic_trace still holds it,
# so the report still shows it, in the error-output section.
#
# `tee` runs in the background, rather than as an element of a pipeline, so
# that `cronic` need not wait for it.  `tee` finishes only when every process
# that holds the subshell's stderr has closed it, so a background process that
# the command started without redirecting its stderr, such as a server started
# by `nohup` (which redirects stderr only when it is a terminal), would make
# `cronic` wait until that process exits.  So after the subshell finishes,
# `cronic` waits at most 5 seconds for `tee`, which is ample time for `tee` to
# copy what the subshell wrote.  Then, if `tee` is still running, `cronic`
# replaces it by a process that discards what the background process writes to
# its stderr, so that the background process does not get SIGPIPE and the
# temporary files do not grow; then `cronic` reports.  `tee` writes its own
# error messages to a file, which `cronic` copies to its stderr, rather than to
# `cronic`'s stderr directly, so that a `tee` that is still running does not
# hold `cronic`'s stderr, for which cron waits before sending mail.  `tee` is
# not run in a process substitution `2> >(tee ...)`, because bash 3.2 does not
# set `$!` to the process id of a process substitution.
#
# `tee` ignores the signals that `cronic` handles.  `cronic` and `tee` are in
# the same process group, and so receive the same signal when it is sent to
# that group, as by Ctrl-C or by a supervisor that stops a service.  If such a
# signal killed `tee`, then a command that survives the signal, such as one that
# handles it by writing a message to stderr and cleaning up, would itself be
# killed by SIGPIPE when it next wrote to stderr.  `tee` still finishes when
# the command does.
#
# The subshell is not the operand of `||` or the like, because then bash would
# ignore `set -e` throughout the subshell, including in a shell function that it
# runs, and would remove "errexit" from the SHELLOPTS that the command inherits.
#
# Limitation:  if the command is a builtin that runs code in the subshell, such
# as `source` or `eval`, that code runs with the caller's options even if the
# caller does not export SHELLOPTS.  So if the caller does not use `set -u`,
# that code silently expands an unset variable to the empty string.
mkfifo "$cronic_stderr_fifo"
(
  trap '' HUP INT TERM
  exec tee "$cronic_trace" < "$cronic_stderr_fifo"
) >> "$cronic_combined" 2> "$cronic_tee_err" &
cronic_tee_pid=$!
set +e
(
  # shellcheck disable=SC2046  # each name is a separate argument.
  unset -f $(compgen -A function)
  eval "unset -v \"\${!cronic_@}\" || exit 1
    $cronic_caller_functions
    ${cronic_caller_function_names:+builtin export -f --$cronic_caller_function_names}
    builtin set +u${cronic_caller_flags:+ -$cronic_caller_flags}"
  "$@"
) >> "$cronic_combined" 2> "$cronic_stderr_fifo"
cronic_result=$?
set -e

# Wait at most 5 seconds, in steps of a tenth of a second, for `tee` to finish.
cronic_tenths=0
while kill -0 "$cronic_tee_pid" 2> /dev/null && [ $cronic_tenths -lt 50 ]; do
  sleep 0.1
  cronic_tenths=$((cronic_tenths + 1))
done
cronic_stop_tee
cat "$cronic_tee_err" >&2

# The command wrote no standard output if and only if the combined output is
# as long as the error output, because the combined output is the standard
# output and the error output, appended.  This is checked before a newline is
# appended to either file, below.
if [ "$(wc -c < "$cronic_combined")" -eq "$(wc -c < "$cronic_trace")" ]; then
  cronic_has_stdout=0
else
  cronic_has_stdout=1
fi

# Appends a newline to the given file, if the file is not empty and does not
# end with a newline.
cronic_end_with_newline() {
  if [ -s "$1" ] && [ "$(tail -c 1 "$1" | wc -l)" -eq 0 ]; then
    echo >> "$1"
  fi
}

# End the combined output with a newline, so that its last line is not on the
# line of the report's next heading.
cronic_end_with_newline "$cronic_combined"

# Unsetting BASH_XTRACEFD also closes its file descriptor.
unset BASH_XTRACEFD

# With the caller's xtrace on, the first line of the trace file is the trace of
# the `"$@"` line above, which is this script's, not the command's, so it is
# removed.  (The `set` command before it is not traced.)  For a builtin
# COMMAND, such as `exit`, that line is the builtin's own trace.  If PS4
# contains a newline, then that trace spans several lines, of which only the
# first is removed.  A bash before 4.1 writes the trace to stderr, and that line
# is not removed from it.
if [ -n "${cronic_xtrace_fd-}" ] && [[ $cronic_caller_flags == *x* ]]; then
  sed 1d "$cronic_xtrace" > "$cronic_xtrace.reduced"
  cronic_xtrace=$cronic_xtrace.reduced
fi

# End stderr with a newline, if it is not empty.  `grep` ends its output with a
# newline, so without this, the filtered stderr would differ from the
# unfiltered stderr even when `grep` removed no line, and the report would
# show the same output twice.  The newline also keeps the last line of stderr
# off the line of the report's next heading.
cronic_end_with_newline "$cronic_trace"

# Prints a basic regular expression that matches its argument literally.
# The argument must not contain a backslash.
cronic_bre_quote() {
  printf '%s\n' "$1" | LC_ALL=C sed 's/[*.[^]/\\&/g'
}

# Prints a basic regular expression that matches the trace lines, for PS4, that
# a shell other than bash 4.1 or later writes to stderr.  Such a line starts
# with PS4 after expansion, with PS4's first character repeated once per level
# of nesting.  If PS4 contains a `$`, backquote, or backslash, then its
# expansion can differ from line to line, so nothing is printed:  any pattern
# for such a PS4 could also match, and hide, a real error.  Nothing is printed
# if PS4 contains a newline, either, because `grep` would treat each line of
# the pattern as a separate pattern.
cronic_trace_pattern() {
  case ${PS4-} in
    '' | *[\$\`\\]* | *$'\n'*) return ;;
  esac
  # In the C locale, a character is a byte.  The first character is a UTF-8
  # lead byte and its continuation bytes, or else a single byte, so that a
  # multibyte character is repeated as a whole, whatever the locale.
  local LC_ALL=C
  [[ $PS4 =~ ^([$'\xc0'-$'\xff'][$'\x80'-$'\xbf']*|.) ]]
  local first=${BASH_REMATCH[0]}
  local rest=${PS4#"$first"}
  # `\{1,\}` rather than GNU's `\+`, which is not a POSIX basic regular
  # expression.
  printf '^\\(%s\\)\\{1,\\}%s\n' "$(cronic_bre_quote "$first")" "$(cronic_bre_quote "$rest")"
}

# Each `grep` that reads the wrapped command's output uses `-a`, so that it
# treats the output as text even if it contains a NUL byte or a byte that is
# invalid in the locale.  Without `-a`, `grep` would treat such output as
# binary and print only a "Binary file ... matches" notice in place of the
# lines it selects, so that a real error could go unreported.
cronic_pattern=$(cronic_trace_pattern)
if [ -n "$cronic_pattern" ]; then
  # `|| [ $? -eq 1 ]` because `grep -v` exits with status 1 when it selects no
  # lines, which happens whenever stderr consists only of trace lines.  Without
  # it, `set -e` would abort the script here, before it produces its report,
  # and it would exit with status 1 rather than with the wrapped command's
  # status.  If `grep` fails (status 2), the unfiltered stderr is used, rather
  # than an empty or truncated file cronic_err that could hide an error.
  grep -a -v "$cronic_pattern" "$cronic_trace" > "$cronic_err" || [ $? -eq 1 ] || cronic_err=$cronic_trace
else
  cronic_err=$cronic_trace
fi

# Certain Unix programs send output to stderr even when a command is successful!
# For example, git does this, and the POSIX standard requires it for make.
# The full stderr output is shown, but file cronic_reduced_err is checked for
# emptiness below.
#
# GNU make names itself by the name it was invoked as, without the directory,
# such as `make`, `gmake`, `gnumake` (on macOS), or `mingw32-make`.  It quotes
# the directory as 'dir' from version 4.0, and as `dir' before then; macOS's
# /usr/bin/make is GNU make 3.81.
# TODO: Expand this.
#
# `|| [ $? -eq 1 ]` because `grep -v` exits with status 1 when it selects no
# lines.  If `grep` fails (status 2), the unreduced stderr is used.
grep -a -E -v \
  -e '^Everything up-to-date$' \
  -e '^[[:alnum:]_.-]*make(\[[0-9]+\])?: (Entering|Leaving) directory '"[\`']"'.*'"'"'$' \
  "$cronic_err" > "$cronic_reduced_err" || [ $? -eq 1 ] || cronic_reduced_err=$cronic_err

if [ "$cronic_result" -ne "$cronic_expected" ] || { [ $cronic_permitstderr -eq 0 ] && [ -s "$cronic_reduced_err" ]; }; then
  echo "Cronic detected failure or error output for the command:"
  echo "$@"
  echo
  if [[ $cronic_expected -eq 0 ]]; then
    if [[ $cronic_result -eq 0 ]]; then
      echo "RESULT CODE: $cronic_result  (success)"
    else
      echo "RESULT CODE: $cronic_result  (failure)"
    fi
  else
    echo "RESULT CODE: $cronic_result  (expected: $cronic_expected)"
  fi
  echo
  echo "ERROR OUTPUT:"
  cat "$cronic_err"
  echo
  if [ "$cronic_debug" != "true" ]; then
    if ! cmp -s "$cronic_err" "$cronic_reduced_err"; then
      echo "REDUCED ERROR OUTPUT:"
      cat "$cronic_reduced_err"
      echo
    fi
  fi
  # Without standard output, this section would repeat the error output.
  if [ $cronic_has_stdout -eq 1 ]; then
    echo "STANDARD AND ERROR OUTPUT:"
    cat "$cronic_combined"
    echo
  fi
  if ! cmp -s "$cronic_trace" "$cronic_err"; then
    echo "TRACE-ERROR OUTPUT:"
    cat "$cronic_trace"
    echo
  fi
  if [ -s "$cronic_xtrace" ]; then
    echo "TRACE OUTPUT:"
    cat "$cronic_xtrace"
    echo
  fi
  if [ $cronic_duplicate_stderr -eq 1 ]; then
    echo "ERROR OUTPUT:"
    cat "$cronic_err"
    echo
  fi
  echo "END OF CRONIC OUTPUT."
fi

# The temporary files are removed by the EXIT trap.

exit "$cronic_result"
