]> arthur.barton.de Git - ax-unix.git/blob - mail/wrapper/mail-wrapper
mail-wrapper: Fix some spelling errors in comments
[ax-unix.git] / mail / wrapper / mail-wrapper
1 #!/usr/bin/env bash
2 #
3 # mail-wrapper -- Report results of a command by email
4 # Copyright (c)2017,2018,2023 Alexander Barton (alex@barton.de)
5 #
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
10 #
11
12 NAME=$(basename "$0")
13
14 # Include "ax-common.sh":
15 ax_common_sourced=
16 for dir in "$HOME/lib" "$HOME/.ax" /usr/local /opt/ax /usr; do
17         [ -z "$ax_common_sourced" ] || break
18         ax_common="${dir}/lib/ax/ax-common.sh"
19         # shellcheck source=/usr/local/lib/ax/ax-common.sh
20         [ -r "$ax_common" ] && . "$ax_common"
21 done
22 if [ -z "$ax_common_sourced" ]; then
23         echo "Error ($NAME): \"ax-common.sh\" not found, aborting!" >&2
24         echo "Please install 'ax-unix', \"Alex' UNIX Tools & Scripts\", and try again."
25         exit 99
26 fi
27 unset dir ax_common ax_common_sourced
28
29 usage() {
30         {
31                 echo
32                 echo "Usage:"
33                 echo "  $NAME [--help|--usage]"
34                 echo "  $NAME {parameters} [<command> [<arg> [<…>]]]"
35                 echo
36                 echo "  -C                      Use the \"C\" locale, no localized (error) messages."
37                 echo "  --dontfail|-n           Don't return the error code of the command called."
38                 echo "  --errors|-e             Generate email on errors only."
39                 echo "  --from|-f               Email address of the sender of the email."
40                 echo "  --stderr-is-warning|-W  Exit code indicates error; stderr is only warning."
41                 echo "  --subject|-s <subject>  Subject for the email."
42                 echo "  --to|-t <address>       Email address to send the email to."
43                 echo
44                 echo "When no <command> is given, $NAME reads from standard input."
45                 echo
46         } >&2
47         exit "${1:-0}"
48 }
49
50 syntax_error() {
51         ax_error -l "Syntax error!"
52         usage 2
53 }
54
55 clean_up() {
56         if [[ -z "$proc_fd_works" ]]; then
57                 ax_debug "Cleaning temporary files ..."
58                 [[ -n "$buffer_file" ]] && rm -f "$buffer_file"
59                 [[ -n "$error_file" ]] && rm -f "$error_file"
60         fi
61 }
62
63 case "$(uname)" in
64         "Darwin")
65                 unset proc_fd_works
66                 ;;
67         *)
68                 proc_fd_works=1
69 esac
70
71 # Initialize internal state.
72 buffer_file=""
73 error_file=""
74 error_level=0
75 host=$(hostname -f 2>/dev/null || hostname)
76
77 trap clean_up EXIT
78
79 # Some defaults (can be adjusted by command line parameters).
80 unset do_errors_only
81 unset dont_fail
82 unset stderr_is_warning
83 unset subject
84 from="${LOGNAME:-root} <${LOGNAME:-root}@$host>"
85 to="$from"
86
87 # Parse the command line ...
88 while [[ $# -gt 0 ]]; do
89         case "$1" in
90                 "-C")
91                         unset LANG
92                         export LC_ALL="C"
93                         ;;
94                 "--debug"|"-D")
95                         export DEBUG=1
96                         ;;
97                 "--dontfail"|"-n")
98                         dont_fail=1
99                         ;;
100                 "--errors"|"-e")
101                         do_errors_only=1
102                         ;;
103                 "--from"|"-f")
104                         shift
105                         [[ $# -gt 0 ]] || syntax_error
106                         from="$1"
107                         ;;
108                 "--help"|"--usage")
109                         usage
110                         ;;
111                 "--subject"|"-s")
112                         shift
113                         [[ $# -gt 0 ]] || syntax_error
114                         subject="$1"
115                         ;;
116                 "--stderr-is-warning"|"-W")
117                         stderr_is_warning=1
118                         ;;
119                 "--suppress-empty")
120                         # Ignore this switch for compatibility with an other
121                         # "mail-wrapper" script. This is the default anyway!
122                         ;;
123                 "--to"|"-t")
124                         shift
125                         [[ $# -gt 0 ]] || syntax_error
126                         to="$1"
127                         ;;
128                 "-"*)
129                         syntax_error
130                         ;;
131                 *)
132                         # Command to execute follows in command line.
133                         break
134                         ;;
135         esac
136         shift
137 done
138
139 # Initialize the "buffer file" on file handle #3. This file will store all
140 # output, stdout and stderr combined. The file is immediately unlinked so that
141 # we can't leak stale files. Afterwards this script accesses the "buffer file"
142 # by its file descriptor only.
143 buffer_file=$(mktemp) \
144         || ax_abort -l "Failed to create buffer file: \"$buffer_file\"!"
145 ax_debug "buffer_file=\"$buffer_file\""
146 exec 3>"$buffer_file" \
147         || ax_abort -l "Failed to redirect FD #3 to buffer file!"
148 if [[ -n "$proc_fd_works" ]]; then
149         rm "$buffer_file" \
150                 || ax_error -l "Failed to delete buffer file: \"$buffer_file\"!"
151         buffer_file="/dev/fd/3"
152 fi
153
154 if [[ $# -gt 0 ]]; then
155         # Execute command and save output in buffer file.
156         # Use a sub-shell to not pollute our name space!
157         error_file=$(mktemp) \
158                 || ax_abort -l "Failed to create error buffer file: \"$error_file\"!"
159         ax_debug "error_file=\"$error_file\""
160         exec 4>"$error_file" \
161                 || ax_abort -l "Failed to redirect FD #4 to error file!"
162         if [[ -n "$proc_fd_works" ]]; then
163                 rm "$error_file" \
164                         || ax_error -l "Failed to delete error buffer file: \"$error_file\"!"
165                 error_file="/dev/fd/4"
166         fi
167
168         job=$(basename "$1")
169
170         ax_debug "Running command \"$*\" ..."
171         exit_code=$(
172                 "$@" 2>&1 1>&3 | tee "$error_file" >&3
173                 echo "${PIPESTATUS[0]}"
174         )
175 else
176         # Read from stdin and save it to the buffer file.
177         error_file="/dev/null"
178         job="Job"
179
180         ax_debug "Reading from stdin ..."
181         while read -r line; do
182                 echo "$line" >&3 \
183                         || ax_abort -l "Failed to write to buffer file!"
184         done
185         exit_code=0
186 fi
187
188 ax_debug "exit_code=$exit_code"
189
190 declare -i count_all count_err
191 count_all=$(wc -l <"$buffer_file" || ax_abort -l "Failed to count buffer file!")
192 count_err=$(wc -l <"$error_file" || ax_abort -l "Failed to count error file!")
193
194 # Error or no error -- that's the question! An error is assumed when either the
195 # exit code of the command was non-zero or there was output to stderr.
196 # But when stderr_is_warning is set, messages on stderr result on a warning only!
197 if [[ $exit_code -ne 0 ]]; then
198         error_level=2
199 elif [[ $count_err -gt 0 ]]; then
200         [[ -n $stderr_is_warning ]] && error_level=1 || error_level=2
201 else
202         error_level=0
203 fi
204
205 # Construct email subject ...
206 [[ -z "$subject" ]] && subject="$host: $job report"
207 if [[ "$error_level" -eq 0 ]]; then
208         subject="$subject - success"
209 elif [[ "$error_level" -eq 1 ]]; then
210         subject="$subject - WARNING!"
211 else
212         subject="$subject - ERROR!"
213 fi
214
215 ax_debug "from=\"$from\""
216 ax_debug "to=\"$to\""
217 ax_debug "subject=$subject"
218
219 if [[ -n "$DEBUG" ]]; then
220         echo "--- stdout+stderr ---"
221         cat "$buffer_file"
222         echo "--- stderr ---"
223         cat "$error_file"
224         echo "---"
225 fi
226
227 ax_debug "count_all=$count_all"
228 ax_debug "count_err=$count_err"
229 ax_debug "error_level=$error_level"
230
231 # No errors detected (exit code & stderr), and email should be sent on errors
232 # only: so exit early!
233 [[ "$error_level" -lt 2 && -n "$do_errors_only" ]] && exit $exit_code
234
235 # No error detected and no output at all: skip email, exit early:
236 [[ "$error_level" -eq 0 && $count_all -eq 0 ]] && exit $exit_code
237
238 # Build the report mail.
239 # Make sure to ignore all mail(1) configuration files, system wide /etc/mailrc
240 # (by using the "-n" option) as well as ~/.mailrc (by setting the MAILRC
241 # environment variable).
242 export MAILRC=/dev/null
243 (
244         echo "$job report:"
245         echo
246         echo " - Host: $host"
247         echo " - User: $(id -un)"
248         echo " - Exit code: $exit_code"
249         echo
250         if [[ $# -gt 0 ]]; then
251                 # A command name is known (not stdin), show it!
252                 echo "Command:"
253                 echo "$@"
254                 echo
255         fi
256         if [[ $count_err -gt 0 ]]; then
257                 # Prefix mail with all error messages.
258                 echo "Error summary:"
259                 echo "-----------------------------------------------------------------------------"
260                 cat "$error_file" \
261                         || ax_abort -l "Failed to dump error file!"
262                 echo "-----------------------------------------------------------------------------"
263                 echo
264         fi
265         if [[ $count_all -ne $count_err ]]; then
266                 # Show full output when different to "error output" only.
267                 cat "$buffer_file" \
268                         || ax_abort -l "Failed to dump buffer file!"
269         fi
270 ) | mail -n -a "From: $from" -s "$subject" "$to" \
271         || ax_abort -l "Failed to send email to \"$to\"!"
272
273 [[ -n "$dont_fail" ]] && exit 0 || exit $exit_code