server-scripts/mail_wrap_script.sh

67 lines
1.4 KiB
Bash
Raw Normal View History

#!/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 "$(hostname) $SCRIPT failure"
echo "Sent"
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 "$(hostname) $SCRIPT log"
echo "Sent"
fi