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