87 lines
2.2 KiB
Bash
Executable File
87 lines
2.2 KiB
Bash
Executable File
#!/bin/bash
|
|
|
|
# Default values
|
|
IGNORE_EXIST_CODE=0
|
|
SCRIPT="-1"
|
|
ALWAYS_SEND=0
|
|
|
|
# Get arguments
|
|
while [ $# -gt 1 ]; do
|
|
# single ARG
|
|
ARG_NAME=$1
|
|
shift
|
|
|
|
case $ARG_NAME in
|
|
--always-send)
|
|
ALWAYS_SEND=1
|
|
continue
|
|
;;
|
|
esac
|
|
|
|
# ARG + VALUE
|
|
ARG_VALUE=$1
|
|
shift
|
|
|
|
case $ARG_NAME in
|
|
--ignore-exit-code)
|
|
IGNORE_EXIT_CODE=$ARG_VALUE
|
|
;;
|
|
--script)
|
|
SCRIPT=$ARG_VALUE
|
|
break
|
|
;;
|
|
esac
|
|
done
|
|
|
|
# Exit if bad script
|
|
if [ "$SCRIPT" = "-1" ]; then
|
|
echo No script specified
|
|
echo "Sending error mail"
|
|
echo -e "No script specified\n\n\n $(ps $PPID)" | $(dirname $0)/mail.sh "[CRITITCAL] $(hostname) undefined script"
|
|
echo "Sent"
|
|
exit 1
|
|
fi
|
|
|
|
# Create temp logfile
|
|
FILE_ID=$(cat /dev/urandom | tr -dc 'a-z0-9' | fold -w 32 | head -n 1)
|
|
touch /tmp/$FILE_ID.log
|
|
chmod a-rwx,u+r /tmp/$FILE_ID.log
|
|
|
|
# Execute script with remaining arguments
|
|
$SCRIPT "$@" 2>&1 | tee /tmp/$FILE_ID.log
|
|
ERR=${PIPESTATUS[0]}
|
|
OUTPUT=$(cat /tmp/$FILE_ID.log)
|
|
rm /tmp/$FILE_ID.log
|
|
|
|
# Send mail in case of error
|
|
if [ $ERR -ne 0 ] && [ "$ERR" != "$IGNORE_EXIT_CODE" ]; then
|
|
echo "Sending error mail"
|
|
echo -e "An error occured during the execution of $SCRIPT ($ERR).\n\n\n$(ps $PPID)\n\n$OUTPUT" | $(dirname $0)/mail.sh "[E] $(hostname) $SCRIPT"
|
|
|
|
if [ $? -eq 0 ]; then
|
|
echo "Sent"
|
|
else
|
|
echo "Could not send mail, sending safe-body mail..."
|
|
attachment=$(mktemp log.XXXXXXXXX.txt.zstd)
|
|
echo -e "$OUTPUT" | zstd > $attachment
|
|
echo -e "An error occured during the execution of $SCRIPT ($ERR).\n\n\n$(ps $PPID)\n\n(Too long log was attached as a file)" | $(dirname $0)/mail.sh "[E] $(hostname) $SCRIPT" "$attachment"
|
|
rm "$attachment"
|
|
echo "Sent"
|
|
fi
|
|
exit 1
|
|
elif [ $ALWAYS_SEND -ne 0 ]; then
|
|
echo "Sending log mail"
|
|
echo -e "Logging execution of $SCRIPT ($ERR).\n\n\n$(ps $PPID)\n\n$OUTPUT" | $(dirname $0)/mail.sh "[I] $(hostname) $SCRIPT"
|
|
|
|
if [ $? -eq 0 ]; then
|
|
echo "Sent"
|
|
else
|
|
echo "Could not send mail, sending safe-body mail..."
|
|
attachment=$(mktemp log.XXXXXXXXX.txt.zstd)
|
|
echo -e "$OUTPUT" | zstd > $attachment
|
|
echo -e "Logging execution of $SCRIPT ($ERR).\n\n\n$(ps $PPID)\n\n(Too long log was attached as a file)" | $(dirname $0)/mail.sh "[I] $(hostname) $SCRIPT" "$attachment"
|
|
rm "$attachment"
|
|
echo "Sent"
|
|
fi
|
|
fi
|