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